函数模板链接错误

Function template linking error

本文关键字:错误 链接 函数模板      更新时间:2023-10-16

我创建了一个函数模板,允许我获得任何数据类型的数据,但在编译时收到错误消息:

Undefined symbols for architecture i386:
  "bool Json::getData<double>(double, Json&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, DataType)", referenced from:
      Coupon::initCoupon(int const&, Json&)in libkuapay.a(Coupon.o)
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
scons: *** [kuaposgw] Error 1
scons: building terminated because of errors.

函数声明为:

 template < class T> static bool getData(T data, Json &jsonObject, const string &key, DataType dataType);

被称为:

 Json::getData (couponList[cpnCnt].discount, couponReader, "discount", realType);

其中couponList[cpnCnt].discount为双精度体。

代码本身在我的"内部"目录中编译得很好,但我在

模板的当前状态通常要求在有函数声明的地方有函数定义

模板的工作方式是,编译器基本上为模板参数的每个变体生成一个自定义版本的函数。因为编译器不能提前知道所有这些不同的模板参数是什么(它是int还是double,还是在其他文件中声明的未知类型?),它不能创建这些版本,直到函数被调用。

这意味着在调用函数时,编译器必须对整个函数定义可用。为了实现这一点,您应该将函数定义放在头文件中。

还有其他方法可以做到这一点。类模板的显式实例化。声明一个重载,其中没有函数的模板参数。但一般来说,你的整个模板定义必须在头文件中

模板在c++中不是自动实例化的,而是隐式使用或显式实例化的。你可以通过在模板实例化可用时使用该函数来触发前一种情况(例如,通过将其放在头文件中),就像上面描述的@Omnifarious一样。

作为一种替代方法,您可以将函数设置为非static,并在源文件中显式地实例化它:

template bool getData<double>(double data, Json &jsonObject, const string &key, DataType dataType);
相关文章: