【问题标题】:Clang won't compile a template specialization that gcc willClang 不会编译 gcc 会的模板特化
【发布时间】:2019-01-17 15:06:49
【问题描述】:

Gcc 编译得很好,但是 Clang (trunk) 拒绝了这个消息:

<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> { };

这段代码是否正确?

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多