头文件中模板显式实例化

Template explicit instantiation in header

本文关键字:实例化 文件      更新时间:2023-10-16

我知道可以在头文件中声明模板,并在源文件中定义它,只要我提前声明它将被实例化的参数。我的问题是:将显式实例化在。h文件创建问题?它似乎可以工作,但我总是看到人们把它们放在源文件中,而不是在。h

中。

我想说的是

. h文件
class foo
{
public:
    template <typename T>
    void do(const T& t);
};
template<> void foo::do<int>(const int&);
template<> void foo::do<std::string>(const std::string&);

. cpp文件
template <int>
void foo::do(const int& t)
{
    // Do something with t
}
template <std::string>
void foo::do(const std::string& t)
{
    // Do something with t
}

这些称为显式专门化。显式实例化是另一回事。

将这些声明放在头文件中是好的,也是一个非常好的主意。当编译其他源文件时,您希望编译器知道不要使用主模板生成那些专门化。

*.cpp文件中的语法是错误的。定义应该更像下面的声明:

template <>
void foo::do<int>(const int& t)
{
    // Do something with t
}