joergbrech
joergbrech

Reputation: 2792

MSVC instantiates class template in constexpr-if statement which shouldn't be instantiated

I have a piece of code that compiles with GCC and Clang, but not with MSVC and I can't figure out why. The problem is that MSVC instantiates a class template in the constexpr-if statement which GCC and Clang do not instantiate.

I boiled it down as good as I can, please bear with me if the boiled down example doesn't make much sense.

#include <type_traits>

class Foo
{
public:
    virtual void foo() = 0;
protected:
    virtual ~Foo(){}
};

template <typename E>
struct Bar : public Foo
{

    Bar(E const& e) : value(e) {}

    void foo() override final {
        bool x = std::is_pointer_v<E>;
    }

    E value;
};

template <typename T>
void some_function(){

    auto inner_lambda = []() {
        if constexpr (!std::is_abstract_v<T>) 
        {
            // why does MSVC instantiate this template?
            Bar<T> u;
        }
    };
};

class Base {
public:
    virtual void fun() = 0;
protected:
    virtual ~Base(){}    
};

int main()
{
    some_function<Base>();
    return 0;
}

Compiler error

<source>(22): error C2282: 'Bar<T>::~Bar' cannot override 'Foo::~Foo'
        with
        [
            T=Base
        ]
<source>(17): note: while compiling class template member function 'void Bar<T>::foo(void)'
        with
        [
            T=Base
        ]
<source>(31): note: see reference to class template instantiation 'Bar<T>' being compiled
        with
        [
            T=Base
        ]
<source>(45): note: see reference to function template instantiation 'void some_function<Base>(void)' being compiled
Compiler returned: 2

Interestingly, I couldn't boil down the example much further:

All of these seem unrelated to me, so this smells a lot like a compiler bug. Am I wrong?

Here is a Godbolt link

Upvotes: 0

Views: 174

Answers (1)

Alan
Alan

Reputation: 1

The program is well-formed. Note that the program is accepted by msvc if you either change to c++20 from msvc v19.32 onwards or if we use latest version of msvc with c++17.

this smells a lot like a compiler bug. Am I wrong?

Yes, it is a msvc bug that has been fixed with the latest version. Here is the corresponding bug report:

MSVC rejects valid program involving constexpr if

Upvotes: 1

Related Questions