Adr*_*ian 0 c++ static-assert c++11
如果USE_STATIC_ASSERT是0,则按预期工作(从列表中获取索引类型).如果1 static_assert()总是跳闸.我本以为static_assert()只有当所有人typename都筋疲力尽时才会发生.为什么不是这样?
#define USE_STATIC_ASSERT 1
template <unsigned int I, typename ...Ts>
struct items;
template <typename T, typename ...Ts>
struct items<0, T, Ts...>
{
typedef T type;
};
template <unsigned int I, typename T, typename ...Ts>
struct items<I, T, Ts...> : items<I-1, Ts...>
{
};
#if USE_STATIC_ASSERT
template <unsigned int I>
struct items<I>
{
static_assert(false, "Ran out of Ts.");
};
#endif
int main()
{
cout << is_same<float, items<1, int, float, double>::type>::value << endl;
}
Run Code Online (Sandbox Code Playgroud)
即使items包含的部分特static_assert化没有实例化,也允许编译器根据§14.6[temp.res]/p8拒绝此代码:
知道哪些名称是类型名称允许检查每个模板的语法.不能为可以生成有效特化的模板发出诊断.如果无法为模板生成有效的专业化,并且未实例化该模板,则模板格式错误,无需诊断.
要解决此问题,您可以使表达式static_assert依赖于其他类模板:
#include <type_traits>
template <unsigned int I>
struct AlwaysFalse : std::false_type {};
template <unsigned int I>
struct items<I>
{
static_assert(AlwaysFalse<I>{}, "Ran out of Ts.");
// ~~~~~~~~~~~~~~~^
};
Run Code Online (Sandbox Code Playgroud)