c++ - Clang 不会编译 gcc 会编译的模板特化

标签 c++ gcc clang language-lawyer template-specialization

Gcc 可以正常编译,但 Clang(主干)拒绝并显示以下消息:

<source>:7:8: error: class template partial specialization is not more specialized than the primary template [-Winvalid-partial-specialization]

https://godbolt.org/g/h8rsWC

template<class T, T x>
struct S{};

template<int& x>
struct S<int&, x> { };

这段代码是否正确?

最佳答案

这仅在 -std=c++17 及更高版本中出现。 “更专业”的确定需要 synthesizing a pair of function templates from the class templates , synthesizing unique types, values, and templates for the template parameters ,最后 performing template argument deduction in both directions .如果演绎在一个方向上成功但在另一个方向上失败,则模板“更专业”。

在这里,Clang 从两个来源推导出 T 并得到不同的结果:

  • 从明确指定的int&,它推导出T := int&
  • 从非类型参数x,它根据通常的推导规则(通常不推导引用类型)推导T := int。这种从非类型模板参数的类型推断的能力是在 C++17 中添加的。

这使得推导在两个方向上都失败了,因此部分特化无法通过“更特化”的测试。

这看起来像是标准中的缺陷。解决方法是将原始模板中的 T 包装在非推导上下文中。

关于c++ - Clang 不会编译 gcc 会编译的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51779059/

相关文章:

c++ - 使用 CMake 查找使用 CLang 编译的 Boost

c++ - python <=> c++ 跨语言哈希

c++ - 当有符号/无符号不匹配时会发生什么转换?

c++ - 在主函数 c++ 中使用类时出现两个错误

c - GCC、重复的 typedef 和 DWARF

ubuntu - 如何在ubuntu14.04上安装clang

C++ 在图像格式之间转换的快速方法

gcc - 拦截 GNU tar 的 openat() 系统调用

c++ - caffe 安装 : gcc error namespace "std" has no member "isnan"

gcc - 如何使用 clang 指定库搜索路径