gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:32:24 25 4
gpt4 key购买 nike

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

/* --- 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com