上下文
我们开发了一个模板化的设置系统类,它将成为我们向不同架构的用户公开的 API 的一部分(简而言之:我们不应该依赖特定于编译器的行为)
通用代码如下:
在标题中
namespace Firm
{
// Class definition
class A
{
template<class T>
void foo(T* aParam);
};
// Non specialized template definition
template<class T>
void A::foo(T* aParam)
{
//...
}
// Declaration of a specialization
template<>
void A::foo<int>(int* aParam);
} // namespace
在CPP文件中
namespace Firm
{
// Definition of the specialized member function
template<>
void A::foo<int>(int* aParam)
{
//...
}
} // namespace
问题
gcc 4.x 一切正常。 (即不同的编译单元在适当的时候使用专门的方法。)但是我读到以下条目后感到不舒服:
Visibility of template specialization of C++ function
接受的答案指出,如果我正确理解它,如果模板方法的特化定义从调用中不可见,那么这是一个错误网站。 (所有不是上面列出的CPP文件但包括头文件的编译单元都是这种情况)
我不明白为什么此时声明还不够( header 提供的声明)?
如果它确实是一个错误,是否有正确的方法来定义它的特化:
- 非内联
- 可用于包含 header (以及与相应 .obj 的链接)的任何编译单元?
最佳答案
将声明放在头文件中。
编译器要么需要实例化模板(需要定义)要么你需要使用c++0x extern模板
看这里:https://stackoverflow.com/a/8131212/258418
编辑 @单一定义规则: 你应该没问题,因为我对模板进行了以下行为: 在不同的 o 文件中创建它们(多次,由于多次编译而耗时),当链接器进入时,它会删除重复项并使用一个实例化。
另请查看此答案/wiki 链接:https://stackoverflow.com/a/8133000/258418
edit2
对于类,它是这样工作的:
extern template class yourTemplate<int>; //tell the compiler to just use this like a funciton stub and do no instantiation. put this in the header
template class yourTemplate<int>; //instantiation, put this in a c file/object that you link with the project
对于您的功能,它应该像这样工作: //在你的标题中声明一个特化 外部模板<> void A::foo(int* aParam);
//in your cpp file
template<>
void A::foo<int>(int* aParam) {
code...
}
template class A::foo<int>(int* aParam);
关于c++ - 如何专门化非内联模板化成员函数? (用于不同的翻译单元),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8803651/