Short-circuiting while instantiating template?

前端 未结 1 1362
故里飘歌
故里飘歌 2021-01-02 02:40

Consider this code snippet,

template
struct other
{
    static const bool value = !b;
};

template
struct test
{
    static const         


        
相关标签:
1条回答
  • 2021-01-02 02:53

    According to the C++ spec, section $14.7.1/4:

    "A class template specialization is implicitly instantiated if the class type is used in a context that requires a completely-defined object type or if the completeness of the class type affects the semantics of the program; in particular, if an expression whose type is a class template specialization is involved in overload resolution"

    In the case you illustrated with short-circuiting, the class would have to have a complete type, because you're looking inside of it to find the value static member. This precludes the compiler from short-circuiting the expression.

    As for what actually happens in practice, I'm not sure because I can't see how the compiler could get away with not doing the instantiation. For example, suppose that the instantiation of other<b> looked like this:

    template <bool B> struct other {
        typedef int value;
    };
    

    Here, your program would be ill-formed because other<b>::value is a type, not a value, but the compiler couldn't diagnose the error without actually doing the instantiation.

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