Static_assert and class templates

I have a problem with a function static_assert

. When I create the template template directly, everything works as expected. But when I pass it as a parameter to another class template static_assert

doesn't 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 everyone for the answers. Is there a way to explicitly instantiate A without instantiating A / inheriting from A? I tried to do 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 not true.

+3


source to share


2 answers


For B<A<1>> b;

, is A<1>

used only as a template argument that does not implicitly create a class template A

, then the definition static_assert

inside A

will not be run.

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

On the other hand, A<1> a;

it is required to A<1>

be a complete type (for construction A

), then implicit instantiation occurs, static_assert

starts.



EDIT

You can use sizeof

(which requires the type to be complete) to invoke implicit instantiation and run static_assert

. eg.

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

      

+4


source


Your template template B

does nothing with it T

, so it is T

not generated.

Thus, "nothing happens" with A<1>

c B<A<1>>

.



If you have a member T a

inside B

, you will get an assertion error.

+1


source







All Articles