A 相关问题提供了类型无关的示例false
in a static_assert
:
template<class T> void foo()
{
if constexpr(false)
static_assert(false);
}
但是,我更担心同样的事情是否适用于类型相关的false
。以下是该标准的相关引用:
该计划是格式错误,无需诊断,如果无法为模板生成有效的专业化或模板中 constexpr if 语句的子语句并且模板未实例化。§ 13.7/8.1
这让我感到惊讶,因为我经常看到以下习语:
template<class T> void foo()
{
if constexpr(cond)
// ...
else
static_assert(!std::is_same_v<T, T>);
}
事实上,cppreference甚至提供了一个例子同一事物的:
template<class T> struct dependent_false : std::false_type {};
template<class T> void foo()
{
if constexpr (cond)
// ...
else
static_assert(dependent_false<T>::value);
}
据我了解,在这两种情况下,都无法为相关的专业化生成有效的专业化if constexpr
子陈述,因此格式错误,无需诊断。我对么?
无法为相关的领域生成有效的专业化if constexpr
子陈述
Well no.
如果您专业化,您可以拥有该分支的有效专业化dependent_false
first:
template <> struct dependent_false<int> : std::true_type {};
///
foo<int>(); // <-- A valid specialization for the `else` branch is possible here
事实上,创建这样的专业化是可能的(即使你没有)static_assert(dependent_false<T>::value);
结构良好。
另一方面,static_assert(!std::is_same_v<T, T>);
是格式不正确的 NDR,因为专门的模板来自std::
不允许。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)