头文件中模板显式实例化
Template explicit instantiation in header
我知道可以在头文件中声明模板,并在源文件中定义它,只要我提前声明它将被实例化的参数。我的问题是:将显式实例化在。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
}
相关文章:
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- 将类成员函数的模板定义放在 CPP 文件中C++隐式实例化而不是 .H 允许吗?
- 即使我正在.cpp文件中实例化一个伪对象,.cpp文件内模板函数的定义也不起作用
- 如何使用 c++ 从另一个 cpp 文件中的 main.cpp 调用实例化类
- 如何在C++实现文件中实例化类?
- 模板类静态在最终二进制文件中跨共享库以不同方式实例化是否一致
- 从文件实例化:构造函数采用std:ifstream&作为参数
- 如何将模板定义和实例化分为HPP和IPP文件
- 在头文件中包含std::vector会导致模板实例化错误
- C++ 类文件中的对象实例化
- 模板函数实例化文件
- C++ 无法实例化编解码器以在 txt 文件中写入 unicode
- 从文件描述符实例化套接字对象的非侵入性方法
- 对在头文件中实例化指针感到困惑
- 如何根据对象文件中缺少的符号实例化模板
- 头文件中的模板实例化
- C++ 使用单个输入字节文件的不同部分实例化堆栈上的成员类
- 是否有任何方法可以避免cpp文件中所有方法的重复类实例化
- 如何重定向头文件(到库)以在实例化中包含一些代码
- 使用头文件实例化和使用 c++ 类