Clang不会编译gcc将要使用的模板专业化 [英] Clang won't compile a template specialization that gcc will
问题描述
Gcc可以很好地进行编译,但是Clang(trunk)拒绝了以下消息:
Gcc compiles this fine, but Clang (trunk) refuses with the message:
<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
及更高版本中体现.更专业"的确定需要从类模板中合成一对功能模板,为模板参数合成唯一类型,值和模板,以及最后在两个方向上执行模板参数推导.如果推导在一个方向上成功而在另一方向上不成功,则模板是更专业的".
This only manifests in -std=c++17
and later. The "more specialized" determination requires synthesizing a pair of function templates from the class templates, synthesizing unique types, values, and templates for the template parameters, and finally performing template argument deduction in both directions. A template is "more specialized" if deduction succeeds in one direction but not the other.
在这里,Clang从两个来源推导 T
并得到不同的结果:
Here, Clang is deducing T
from two sources and getting divergent results:
- 从显式指定的
- 推断出
T:= int&
. - 从非类型参数
x
中,按照通常的推导规则(通常不推导引用类型)推导T:= int
.在C ++ 17中添加了从非类型模板参数的类型推论的功能.
int&
中- from the explicitly specified
int&
, it deducesT := int&
. - from the non-type argument
x
, it deducesT := int
per the usual deduction rules (which generally do not deduce a reference type). This ability to deduce from the type of a non-type template argument was added in C++17.
这使得推论在两个方向上均失败,因此部分专业化未通过更专业化"的测试.
This makes the deduction fail in both directions, so the partial specialization fails the "more specialized" test.
这看起来像是标准中的缺陷.解决方法是在非推导上下文中将 T
包裹在原始模板中.
This looks like a defect in the standard. The workaround is to wrap the T
in the original template in a non-deduced context.
这篇关于Clang不会编译gcc将要使用的模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!