gpt4 book ai didi

c++ - 具有实际独立的依赖表达式的 static_assert

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:51 25 4
gpt4 key购买 nike

考虑以下模板:

template <typename T>
void foo() {
static_assert(sizeof(T) == 0, "Now what?");
}

The standard (§7.4) says:

[If the condition to static_assert is false] the program is ill-formed, and the resulting diagnostic message (1.4) shall include the text of the string-literal, […]

(引用自https://stackoverflow.com/a/11048906/560450)

在实践中,static_assert 在我们实例化函数模板 foo 之前不会失败,因为使用模板参数会强制编译器仅在两个期间评估条件-相位查找。因此,除非实例化函数模板,否则上面的代码片段不会被视为格式错误。

另一方面,C++ 中的 sizeof(T) > 0 by definition .因此,条件的值实际上独立于任何模板参数!是否允许“恶意”编译器利用这一事实,并拒绝程序格式错误,而不管 foo 是否实际实例化?

最佳答案

是的,允许但不要求编译器拒绝它。

§14.6 [temp.res]/p8:

If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.

一个简单的解决方法:

template <typename T>
struct foo_protector : std::false_type {};

template <typename T>
void foo() {
static_assert(foo_protector<T>::value, "Now what?");
}

编译器不允许拒绝 foo() 的定义,因为可能有 foo_protector 的特殊化,尚未看到,这样它的 成员为 true。只要您实际上没有编写这样的特化,static_assert 就会按预期触发。

关于c++ - 具有实际独立的依赖表达式的 static_assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com