未找到extern声明的模板专用函数



我正试图实现json序列化库nlohmann::json的克隆作为一种学习体验,但我在用户定义(json<->user type(转换接口方面遇到了问题。

基本上,我希望用户能够重载两个函数:to_json(json&,const-Type&(和from_json(const-json&;,Type&(。然后,库将使用重载解析来调用模板化运算符=和单参数构造函数中的thesis函数。

当我只是直接定义这些函数时,它工作得很好,但当我试图为多个类型(在本例中为类S(创建模板定义时,链接器找不到定义。

我已经尝试过为模板化类的各个实例显式实例化函数,尽管我更希望在最终产品中避免这样做。

我猜这与模板函数与自由函数没有相同的签名有关,但我不知道我能做些什么来让它发挥作用。我错过了什么?我在谷歌上也找不到结果,所以这是一个文档模式还是反模式?

谢谢你。下面我试着在一个简短的例子中尽量减少我的问题。

平均等级

#pragma once
#include <cstdio>
template<size_t i>
class S {
size_t n = i;
};
template<size_t i>
void g(const S<i>& s) {
printf("S<%u>n", i);
}

.cpp类

#include "Class.hpp"
template void g<10>(const S<10>&); // <-- Even with explicitly instanciation
void g(const bool& b) {
printf("%sn", b ? "true" : "false");
}

main.cpp

#include "Class.hpp"
template<typename T>
void f(T t) {
extern void g(const T&);
g(t);
}
int main(int, char**) {
S<10> s;
//f(s); <-- linker error: void g(class S<10> const &) not found.
f(false);
}

g(t)调用中g的名称查找在找到extern void g(const T&);声明后立即停止;它从未看到函数模板的声明。因此,编译器生成一个调用,调用一个名为g的正则非模板函数,调用const S<10>&。但在您的程序中没有定义这样的函数,因此链接器出错。

最新更新