MSVC constexpr 编译器错误?

5

环境: VS 2019, v16.4.3,使用C++17和最新开关

以下代码标准正确吗?或者我做错了什么?它在最新的gcc/clang编译器下可以编译通过,但在MSVC上失败了。(请参见以下错误消息)

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);
}

以下是输出结果:

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_'


错误是指在main()中的第二个static_assert,两条消息指的是thing内部的value()成员函数。
似乎do_mixin_thing()中的static_cast引起了问题。我尝试通过constexpr T const& self() const { return static_cast<T const&>(*this); }mixin添加强制转换,但错误仍然存在。

3
是的,这是MSVC的bug,请报告(类型转换是安全的)。这里有一个不使用模板的更短的复现代码:https://godbolt.org/z/D-hXMw - Barry
1
微妙的区别:你的 mixin 模板类实际上使用了 CRTP。一个 mixin 看起来像这样:template<typename Base> struct mixin : Base {}; /* ... */ struct foo : mixin<bar> {}; 参见 https://dev59.com/xWMl5IYBdhLWcg3wAC2h - alter_igel
https://developercommunity.visualstudio.com/content/problem/908077/valid-static-cast-causing-a-constexpr-failure.html - Mercury Dime
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接