通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分特化

2024-04-23

All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS https://timsong-cpp.github.io/cppwp/n4659/.


考虑以下片段:

#include <type_traits>

template <int N> struct num {};

template <typename> struct A;

// (1)
template <int N> struct A<num<N>> { using type = bool; };

// (2)
template <long N> struct A<num<N>> { using type = char; };

static_assert(!std::is_same_v<long, int>, "");

// (A)
static_assert(std::is_same_v<A<num<1>>::type, bool>, "");

int main() {}

The static_assert at (A)对于 GCC 成功,但对于 Clang 失败:

error: static_assert failed due to 
       requirement 'std::is_same_v<char, bool>' ""

本质上,GCC 选择完美匹配的专业(1),而 Clang 选择专业(2).

类似地,如果我们删除断言和专业化(1):

template <int N> struct num {};

template <typename> struct A;

// (2)
template <long N> struct A<num<N>> { using type = char; };

int main() {
  A<num<1>> a{};
  (void)a;
}

然后 GCC 无法编译该程序,而 Clang 接受它。

GCC:

error: variable '`A<num<1> > a`' has initializer but incomplete type

此行为适用于各种 GCC 和 Clang 版本,以及这些版本上的各种 C++ 语言级别(C++11、C++14、C++17、C++2a)。

Question

  • 上面的第一个片段实际上是格式错误的(不需要诊断吗?),还是 GCC 或 Clang 错误?

我的猜测是,这是格式错误的,但无法应用的相关部分[温度等级规格] https://timsong-cpp.github.io/cppwp/n4659/temp.class.spec拒绝它。也许[温度等级规格]/8.1 https://timsong-cpp.github.io/cppwp/n4659/temp.class.spec#8.1?

[温度等级规格]/8.1与专门化的非类型参数相对应的模板参数的类型不应依赖于专门化的参数。 [示例:[...] — 示例结束 ]


据我所知,第一个片段的格式不正确(并且是诊断是必须的);由于部分特化,编译器应该拒绝该程序 (2)。

[温度扣除类型]/18 https://timsong-cpp.github.io/cppwp/n4659/temp.deduct.type#18适用于此处:

If P有一个包含以下内容的表格<i>,如果类型为i不同 从模板对应的模板参数的类型 由附件命名简单模板 ID,推演失败。 [...]

标准中的相关示例使用函数模板,但在其他方面非常相似。

因此,部分特化 (2) 的模板参数永远无法推导,并且[温度.等级.规格.匹配]/3 https://timsong-cpp.github.io/cppwp/n4659/temp.class.spec.match#3适用:

如果部分特化的模板参数不能 根据其结构推导出模板参数列表和 这模板 ID,该程序格式错误。


有趣的是,我找不到诊断这个问题的编译器,甚至严格模式下的 EDG 也找不到。我们可以推测,大多数编译器编写者认为在这里进行诊断的好处不值得付出努力来实现检查。这可能意味着我们可能会看到上一段中的要求将来发生变化不规范的 to 格式错误,无需诊断。然而,这纯粹是猜测。无论如何,我认为它不会改变格式良好的;我想不出永远不匹配的部分专业化的有效用途。


的措辞[温度扣除类型]/18 https://timsong-cpp.github.io/cppwp/n4659/temp.deduct.type#18决议明确了CWG2091 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#2091.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分特化 的相关文章

随机推荐