模板成员函数的实例化

Instantiation of template member function

本文关键字:实例化 函数 成员      更新时间:2023-10-16

In Class.h:

class Class {
public:
    template <typename T> void function(T value);
};

In Class.cpp:

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

In main.cpp:

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

我得到一个链接错误,因为Class.cpp从未实例化void Class::function<int>(T)。您可以使用以下命令显式实例化模板类:

template class std::vector<int>;

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

谢谢,

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

template void Class::function(int);

template实参可以省略,因为类型演绎适用于函数模板。因此,上面的代码相当于下面的代码,只是更简洁:

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

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

您在Class.cpp中尝试过以下操作吗?

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