c++templatestype-traitsif-constexpr

When does type traits instantiate templates


Why doesn't the static_assert inside Foo get triggered in the following code ?

Doesn't the type trait inside if constexpr need to instantiate Foo<float> & Foo<char> ? https://godbolt.org/z/zTPqxvr6e

#include <iostream>
#include <type_traits>

template <typename T>
struct Foo
{
    static_assert(std::is_same_v<T, int>);
};

int main()
{
    using X = Foo<float>;
    if constexpr (std::is_same_v<X, Foo<char>>)
    {
        std::cout << "Yes\n";
    }
    return 0;
}

Solution

  • Class template is implicitly instantiated when the compiler needs that class to be complete:

    https://eel.is/c++draft/temp.inst#2
    Unless a class template specialization is a declared specialization, the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program.

    None of the expressions in that example requires complete Foo<T>, so it's never instantiated.

    using X = Foo<float>; is just a declaration. And there's no reason why is_same<X, Foo<char>> might need the definition of its arguments.

    You may simply remove the definition of struct Foo, and the example will still be well-formed.