c++ - 跨库的模板函数特化符号匹配

标签 c++ linker shared-libraries template-specialization function-templates

到目前为止,我有一个设置,其中某个函数模板 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/

相关文章:

c++ - 为 codeblocks ide 查找 libgtest 链接器库

c++ - 在我的程序中更改共享库中定义的变量不会从共享库中反射(reflect)出来

c# - 使用与主程序存储在不同文件夹中的引用库 (dll)?

c++ - 仅更改一个元素时如何在排序列表中进行快速排序

linker - 什么是二进制格式的 "Alignment"字段?为什么需要它?

c++ - 未解析的外部符号、头文件原因

c++ - 如何在 automake 脚本中创建共享库 (.so)?

c++ - 如何组合输出流,以便输出一次到达多个位置?

c++ - 返回的对象是临时的还是匿名的,是否会导致内存泄漏?

c++ - 如何将字符串添加到字符串数组