Search code examples
c++templatesinstantiationconstexprstatic-assert

How can A and not A be both true when using static_assert


A very confusing situation involving some constexpr and type traits led me to think the value of an expression is true, when in fact it was both true and false.

https://godbolt.org/z/McYMvxasT


#include <utility>
#include <iostream>

template<typename T>
struct S {

    constexpr int f() const {
        constexpr bool t = std::is_same_v<double, double>;
        static_assert(t);
        static_assert(!t);
        //static_assert(false);

        return 0;
    }

    static const int t = f();
};

int main() {
    //S<int> s;
    //std::cout << S<int>::t;

    return 0;
}

I know that if f() never gets instantiated then static_asserts are skipped but this hypothesis is rejected by uncommenting the line static_assert(false) which does fail. Is this a compiler bug?


Solution

  • A template which is not instantiated and which has no well-formed instantiation is ill-formed with no diagnostic required. The program is invalid but the compiler is not required to diagnose it.