问题描述
我正在尝试创建专门用于某些给定类型的全局函数模板.看起来像这样:
I am trying to create a global function template specialized for some given types. It looks something like that:
A.h (主要模板,模板专业化,外部)
A.h (primary template, template specialization, extern)
template <typename T> void foo() { std::cout << "default stuff" << std::endl; }
template<> void foo<int>() { std::cout << "int stuff" << std::endl; }
extern template void foo<int>();
A.cpp (显式实例化)
template void foo<int>();
B.h
void bar();
B.cpp (包括A.h)
void bar() { foo<int>(); }
main.cpp
foo<int>();
bar();
编译器崩溃了:'void foo()'的多个定义.我认为应该由extern来处理.B编译单元不应实例化foo,而应在链接上使用A实例化时间,不?我在这里弄错了什么?
The compiler crashes on me: "multiple definitions of 'void foo()'. I thought that the extern was supposed to take care of this. The B compile unit should not instantiate foo, and instead use the A instantiation at link time, no? What am I getting wrong here?
请注意,如果我不专门研究foo,代码可以很好地编译.函数专门化和实例化之间是否存在某种冲突?
Note that if I do not specialize foo, the code compiles just fine. Is there some kind of conflict between function specialization and instantiation?
推荐答案
此处不需要extern
来抑制实例化.通过声明显式专业化,您已经在告诉任何调用foo<int>
的代码以使用显式专业化而不是主模板.相反,您只想在A.h中声明专业化,然后在A.cpp中定义它:
You don't need extern
here to suppress instantiation. By declaring an explicit specialization, you're already telling any code that calls foo<int>
to use the explicit specialization rather than the primary template. Instead, you simply want to declare the specialization in A.h and then define it in A.cpp:
// A.h
template <typename T> void foo() { std::cout << "default stuff" << std::endl; }
template <> void foo<int>();
// A.cpp
template <> void foo<int>() { std::cout << "int stuff" << std::endl; }
如果要在某个翻译单元中提供主模板的显式实例化,而不是的显式专业化,则可以使用extern
.
Your use of extern
would be appropriate if you wanted to provide an explicit instantiation of the primary template in some translation unit, and not an explicit specialization.
这篇关于功能模板专门化的显式实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!