【问题标题】:Can template partial specialization narrow the argument type in C++?模板偏特化可以缩小 C++ 中的参数类型吗?
【发布时间】:2022-01-15 09:56:09
【问题描述】:

在下一个程序中,struct template A<int> 有一个特化 A<char>

template <int>
struct A { constexpr operator int() { return 1; } };

template <char c>
struct A<c> { constexpr operator int() { return 2; } };

int main() {
    static_assert( A<1000>{} == 1 ); //ok in Clang and GCC
    static_assert( A<1>{} == 2 ); //ok in Clang only
}
  • Clang 接受整个程序。
  • GCC 接受专业化定义,但在 A&lt;1&gt;{} 中忽略它。
  • MSVC 抱怨这种专业化:
error C2753: 'A<c>': partial specialization cannot match argument list for primary template

演示:https://gcc.godbolt.org/z/Ef95jv5E5

哪个编译器在这里?

【问题讨论】:

  • 我不认为这就是人们在编写标准时所说的部分专业化的意思。所以你会得到各种随机的东西。

标签: c++ templates language-lawyer partial-specialization


【解决方案1】:

活动的CWG issue 1647 正是提到了这种将int 非类型模板参数特化为char 的情况。

它还提到该标准目前缺乏处理主模板中的非类型模板参数与其部分特化之间的类型不匹配的措辞,并且在该问题上存在实现分歧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多