static_assert and class templates

前端 未结 2 1550
悲&欢浪女
悲&欢浪女 2020-12-19 14:45

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 f

相关标签:
2条回答
  • 2020-12-19 15:06

    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");
    };
    
    0 讨论(0)
  • 2020-12-19 15:11

    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.

    0 讨论(0)
提交回复
热议问题