C2057:应为常量表达式

C2057: expected constant expression

本文关键字:常量 表达式 C2057      更新时间:2023-10-16

我无法在VS2013上编译它,但它确实在gcc 4.7.2上编译。我知道VC++在功能方面落后于GCC和CLang,但它到底是什么功能?如果不是,这就是一个bug,不是吗?

template <int N>
struct factorial
{
    static const long value;
    static const long previous = factorial<N - 1>::value; //C2057: expected constant expression
};
template <int N>
const long factorial<N>::value = N*factorial<N - 1>::value;
template <>
struct factorial<0>
{
    static const long value = 1;
};

请不要告诉我如何解决这个问题,因为这不是生产代码,我也不需要。例如,我可以在类中定义值,问题就解决了,但假设我必须在类外定义它(VC2013仍然不支持constexpr)

MSVC没有正确的两阶段模板编译。GCC正确地将factorial<N - 1>::value视为依赖名称,并在第二阶段进行解析,但MSVC必须在第一阶段进行解析。