Using trailing return type to prevent function template instantiation?

124 Views Asked by At

While toying with crude reproductions of some of C++17 if constexpr functionalities, I encountered an issue where using auto seems to trigger the instantiation of a template.

The function template in question contains an assertion which fails as expected when its parameters have certain properties (say sizeof).

In C++17 you could trivially use the if constexpr to protect against instantiating the wrong template in favor of a more appropriate one. This is the behavior I seek to reproduce. And I would like to understand why the trailing return type of the Working() template below does the trick but not the NotWorking() template.

The code is available at: https://godbolt.org/z/7he9hPMaM

As noted @LanguageLawyer, the code can be further reduced to:

template <typename T>
auto* NotWorking() {
    static_assert(sizeof(T) <= 4, "");
    return static_cast<T*>(nullptr);
}

template <typename T>
auto Working() -> T* {
    static_assert(sizeof(T) <= 4, "");
    return static_cast<T*>(nullptr);
}

#define PRODUCE_ERROR

template <typename T>
void not_called_closure_operator(T) {
#if defined(PRODUCE_ERROR)
    NotWorking<long>();
#else
    Working<long>();
#endif
}

Code available at: https://godbolt.org/z/oGqb5v9j4

0

There are 0 best solutions below