简体   繁体   中英

static_assert and class templates

I have a problem with the static_assert feature. When I instantiate a class template directly, everything works as expected. But when I pass it as a parameter for the different class template, static_assert does not work.

template <int X>
class A{
    static_assert(X == 0, "X != 0");
};

template <class T>
class B{

};

B<A<1>> b;           // Static assert does not work
A<1>    a;           // error: static assertion failed: X != 0

EDIT

Thanks all for the answers. Is there a way to explicitly instantiate A without creation of A instances / inheriting from A? I was trying this:

template <int X>
class A{
    static_assert(X == 0, "X != 0");
};

template <class T>
class B;

template <template <int X> class T, int X>
class B<T<X>>{
    template class T<X>;
};

But this is incorrect.

For B<A<1>> b; , A<1> is only used as template argument, which doesn't cause implicit instantiation of class template A , then the static_assert inside A 's definition won't be triggered.

When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed.

On the other hand, for A<1> a; , A<1> is required to be a complete type (to construct a ), then implicit instantiation happens, static_assert is fired.

EDIT

You can use sizeof (which requires the type to be complete) to cause the implicit instantiation and fire the static_assert . eg

template <class T>
class B{
    static_assert(sizeof(T) > 0, "static_assert for implicit instantiation");
};

Your class template B doesn't do anything with its T , so its T isn't instantiated.

Thus "nothing happens" to the A<1> in B<A<1>> .

If you had a member T a inside B then you'd get the assertion failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM