Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
431 views
Welcome To Ask or Share your Answers For Others

1 Answer

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. e.g.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...