c++ 如何显式示例化成员函数模板?

nxowjjhe  于 2024-01-09  发布在  其他
关注(0)|答案(2)|浏览(191)

Class.h中:

  1. class Class {
  2. public:
  3. template <typename T> void function(T value);
  4. };

字符串
Class.cpp中:

  1. template<typename T> void Class::function(T value) {
  2. // do sth
  3. }


main.cpp中:

  1. #include "Class.h"
  2. int main(int argc, char ** argv) {
  3. Class a;
  4. a.function(1);
  5. return 0;
  6. }


我得到一个链接器错误,因为Class.cpp从来没有示例化void Class::function<int>(T)。你可以显式地示例化一个类模板:

  1. template class std::vector<int>;


如何显式示例化非模板类的成员模板?

huwehgph

huwehgph1#

您可以在Class.cpp中使用以下语法:

  1. template void Class::function(int);

字符串
模板参数可以省略,因为类型推导适用于函数模板。因此,上面的等价于下面的,只是更简洁:

  1. template void Class::function<int>(int);


请注意,没有必要指定函数参数的名称-它们不是函数(或函数模板)签名的一部分。

yshpjwxd

yshpjwxd2#

你在Class.cpp中试过以下方法吗?

  1. template void Class::function<int>(int value);

字符串

相关问题