Gcc 可以正常编译,但 Clang(主干)拒绝并显示以下消息:
<source>:7:8: error: class template partial specialization is not more specialized than the primary template [-Winvalid-partial-specialization]
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/