c++ - 如何专门化非内联模板化成员函数? (用于不同的翻译单元)

标签 c++ templates

上下文

我们开发了一个模板化的设置系统类,它将成为我们向不同架构的用户公开的 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文件但包括头文件的编译单元都是这种情况)

  1. 我不明白为什么此时声明还不够( header 提供的声明)?

  2. 如果它确实是一个错误,是否有正确的方法来定义它的特化:

    • 非内联
    • 可用于包含 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/

相关文章:

c++ - 隐式类型转换编译失败,这是为什么?

c++ - 使用 { }, { } 将多个 std::pair 传递给可变参数模板构造函数

具有显式值的 C++ 枚举类

c++ - 使用 QtUdpSocket 的简单通信 c/s 应用程序

c++ - 这个子集和问题的解决方案是如何工作的?

c++ - 如何获取提供 const 重载的函数类型?

c++ - 我可以从 boost::multi_array<T, 2> 得到 T**(c 风格的二维数组) 吗?

c# - Qt 4.7 QRegExp 电子邮件地址验证

c++ - 在 C++ 中实现通用 vector 类

C++无法在构造函数中使用模板化参数转换类