c++ - 专门的模板是否需要专门的声明?

标签 c++ templates linker template-specialization

我想要一个只为某些类型定义的模板化函数,所以我写:

/* --- header file with just a declaration --- */
template<class T>
void myFunction(T arg);

/* --- cpp file with specialized definition --- */
template<>
void myFunction<int>(int arg){
    // mybody
}

但我有点困惑,通读例如this answer . 头文件中的声明是否足以让链接器始终链接到相同的特化(静态链接)?或者我需要添加另一个:

template<>
void myFunction<int>(int arg);

在标题中?

最佳答案

您必须从链接的帖子中查看的部分是:

If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs [...]

您可以通过显式实例化声明创建这样的声明,它告诉编译器显式特化位于其他地方。

在头文件中,您可以将显式实例化声明为

extern template void myFunction(int)

关于c++ - 专门的模板是否需要专门的声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526405/

相关文章:

c# - 使用通用 get 方法扩展 SerializedObject

c - 将特定库与 gcc 链接

c++ - R stats::sd() 与 arma::stddev() 与 Rcpp 实现的性能

c++ - 如何不删除基类对象的拷贝?

c++ - 是否可以在 Visual C++ 中默认禁用增量链接?

c++ - 有没有在模板中使用数值的有效方法?

c++ - 琐碎的整型 const 变量总是可以用作模板值吗?

c++ - 在 Xcode 中为 C++ 项目使用框架头文件

c - IAR 为自定义数据定义内存区域

c++ - 在 C++ 中使用 float 的 Memcpy