gcc v10和v9之间的constexpr区别:错误或功能

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

如果使用gcc v10编译,下面的代码将显示错误,但对于gcc v9,该代码是可以的。

template<auto N>
struct A {
    constexpr auto size() const {
        return N;
    }  
};

template<typename T>
void foo1(const T& a) {
    constexpr auto s = a.size(); // Why error here?
}
template<typename T>
void foo2(T a) {
    constexpr auto s = a.size(); // OK
}
int main() {
    A<10> x1;
    foo1(x1);
    foo2(x1);
    A<x1.size()> x2; // OK
    constexpr auto s = x1.size(); // OK
}

据我所知,在所有情况下,成员函数size()均可称为constexpr。但是在某些情况下,与gcc9相比,gcc10的行为发生了变化:如果参数是由const-ref传递的。我不明白为什么不应该使用constexpr?

另一个例子:

template<auto N>
struct A {
    constexpr auto size() const {
        return N;
    }  
};

template<typename T>
constexpr void foo1(const T& a) {
    constexpr auto s = a.size(); // Why error here?
    return s;
}
template<typename T>
constexpr auto foo2(const T& a) {
    return a.size(); // Why OK here
}
int main() {
    A<10> x1;
    constexpr auto s1 = foo1(x1);
    constexpr auto s2 = foo2(x1);
}

我不明白区别。

c++ constexpr constant-expression
1个回答
2
投票

这是GCC bug 66477。它提到GCC错误地接受了常量表达式中的引用类型参数。

此错误已在GCC 10中修复。


a.size()中提到了为什么在常量表达式中不允许this post的原因。

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