jeudi 1 janvier 2015

Why does the `static_assert` always get invoked?

If USE_STATIC_ASSERT is 0, this works as expected (getting indexed type from the list). If 1 the static_assert() is always tripped. I would have thought that the static_assert() would only happen if all the typenames were exhausted. Why is this not so?



#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;
}

Aucun commentaire:

Enregistrer un commentaire