到目前为止,我有一个设置,其中某个函数模板 getF
在 header 中这样声明
template <typename T> F* getF();
未定义函数体。然后在共享库上,getF
有一些专业..
template<>
F* getF<int>()
{
static int r = 42;
static Finstance(r);
return &Finstance;
}
template<>
F* getF<float>()
{
static float r = 3.14159;
static Finstance(r);
return &Finstance;
}
到目前为止,上面的代码运行良好,就像我在客户端可执行文件上调用 getF<float>()
时一样,链接器将替换为适当的引用,如果库中不存在专门化,则编译将失败并出现链接器错误(这是所需的行为)
但是,现在行为应该有一个小的变化:当结果不是专门用于给定的模板参数时,代码应该构建,但在运行时返回 0。
所以我所做的是更改 getF
的声明像这样:
template <typename T> F* getF() { return 0; }
问题是,现在编译器将在所有情况下使用这个定义,无论库中是否有专门化
Question: Is there some other way to provide some default behaviour for the function at runtime, without moving the specializations to header files?
最佳答案
最好的解决方案是声明该库的显式特化存在。
// All in the same header file:
template <typename T> F* getF() { return 0; }
template <> F* getF<int>();
template <> F* getF<float>();
这满足标准 14.7.3/6 的规则:
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; no diagnostic is required.
关于c++ - 跨库的模板函数特化符号匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24356807/