如何让 MSVC 在 c++20 编译时查看静态 constexpr 成员变量和函数?

问题描述 投票:0回答:1

背景

我试图在编译时在 CRTP 类中访问 constexpr 变量。下面是一个 MVCE。

template <class T>
struct CRTP {
    static constexpr int get_value() { 
        return T::value ; 
    }

    static constexpr int crtp_value = get_value();
};

struct Derived: CRTP<Derived> {
     static constexpr int value = 2;
};

int main() {
    static_assert(Derived::crtp_value == 2, "Should result in 2");
    return 0; 
}

但是我无法在 MSVC 上运行它。我在这里做了不该做的事吗?这适用于其他编译器,请参阅 godbolt 链接:

MSVC 声称:

example.cpp
<source>(3): error C2039: 'value': is not a member of 'Derived'
<source>(7): note: see declaration of 'Derived'
<source>(3): note: the template instantiation context (the oldest one first) is
<source>(7): note: see reference to class template instantiation 'CRTP<Derived>' being compiled
<source>(3): note: while compiling class template member function 'int CRTP<Derived>::get_value(void)'
<source>(3): error C2065: 'value': undeclared identifier
<source>(4): error C3615: constexpr function 'CRTP<Derived>::get_value' cannot result in a constant expression
<source>(3): note: failure was caused by control reaching the end of a constexpr function
<source>(12): error C2131: expression did not evaluate to a constant
<source>(12): note: failure was caused by a read of an uninitialized symbol
<source>(12): note: see usage of 'crtp_value'
Compiler returned: 2

我对此一无所知。

问题

如何从 CRTP 中的派生类访问静态 constexpr 成员变量或成员函数以在 MSVC 中工作?

c++ visual-c++ compiler-errors constexpr crtp
1个回答
0
投票

这似乎有效:

template <class T>
struct CRTP {
    static const int crtp_value;
};
 
template <class T> const int CRTP <T>::crtp_value = T::value;
 
struct Derived : CRTP <Derived> {
    static constexpr int value = 2;
};
 
int main() {
    static_assert(Derived::value == 2, "Should result in 2");
}

应该没有必要,但是嘿。

神箭

© www.soinside.com 2019 - 2024. All rights reserved.