Mercury Dime
Mercury Dime

Reputation: 1601

MSVC constexpr Compiler Bug?

Env: VS 2019, v16.4.3 w/c++17 + latest switches

Is the following code standard correct, or am I doing something wrong? It compiles fine using the latest gcc/clang compilers but fails on MSVC. (see error messages below)

template<typename T>
struct mixin {};

struct thing : mixin<thing>
{
    constexpr explicit thing(int value) : value_(value) {}

    constexpr int value() const { return value_; }

private:
    int value_ = 0;
};

template<typename T>
constexpr auto do_mixin_thing(mixin<T> const& m)
{
    return static_cast<T const&>(m).value() * 10;
}

int main()
{
    constexpr thing t1{ 10 };

    // this works
    static_assert(t1.value() == 10);

    // this fails
    static_assert(do_mixin_thing(t1) == 100);
}

Here's the output:

error C2131: expression did not evaluate to a constant

message : failure was caused by attempting to access a member on an object of dynamic type 'mixin<thing>' in which the member is not defined

message : see usage of 'thing::value_'

The error refers to the 2nd static_assert in main(), and the two messages refer to the value() member function inside of thing.

It seems the static_cast in do_mixin_thing() is what's causing the problem. I tried adding the cast to mixin via constexpr T const& self() const { return static_cast<T const&>(*this); } but the error remains.

Upvotes: 5

Views: 480

Answers (1)

Fedor
Fedor

Reputation: 21347

This has been fixed in Visual Studio 2019 version 16.9. Demo: https://gcc.godbolt.org/z/4Y94co6hW

Thanks to the bug reporter: https://developercommunity.visualstudio.com/t/valid-static-cast-causing-a-constexpr-failure/908077

Upvotes: 1

Related Questions