c++ - GCC 4.9 constexpr 错误的解决方法

标签 c++ c++11 constexpr gcc4.9

我有以下代码片段,它代表了实际更大的代码片段:

#include <iostream>
using namespace std;

template<size_t N> class A {
    public:
        static constexpr size_t getN() {return N;}
};

template<size_t N> class B {
    public:
        void print() { cout << "B created: " << N << '\n';}
};

template <class T> class C {
    public:
        void set(T* a) {
            t_ptr = a;
        }

        void create() {
            constexpr int m = t_ptr->getN();
            B<m> b;
            b.print();
        }

    private:
        T* t_ptr;
};

int main() {
   constexpr int n = 2;
   A<n> a;
   C<A<n> > c;
   c.set(&a);
   c.create();
}

使用 g++ -o main main.cpp -std=c++11 和 GCC/G++ 4.8.3 进行编译,收到预期输出: B 创建:2

但是,使用 GCC/G++ 4.9.1 代码无法编译,输出:

main.cpp: In member function ‘void C<T>::create()’:
main.cpp:27:15: error: the value of ‘m’ is not usable in a constant expression
             B<m> b;
               ^
main.cpp:26:27: note: ‘m’ used in its own initializer
             constexpr int m = t_ptr->getN();
                           ^
main.cpp:27:16: error: the value of ‘m’ is not usable in a constant expression
             B<m> b;
                ^
main.cpp:26:27: note: ‘m’ used in its own initializer
             constexpr int m = t_ptr->getN();
                           ^
main.cpp:27:19: error: invalid type in declaration before ‘;’ token
             B<m> b;
                   ^
main.cpp:28:15: error: request for member ‘print’ in ‘b’, which is of non-class type ‘int’
             b.print();
               ^

这是由 GCC 4.9 中的一个已知错误引起的:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59937在这个旧线程中 https://gcc.gnu.org/ml/gcc-bugs/2013-11/msg00067.html建议使用 extern 作为解决方法。但是,我无法使此解决方法发挥作用。

你们能帮我让这段代码在 GCC 4.9 中编译吗?谢谢!

最佳答案

由于 this 不是 constexpr,因此对 this->t_ptr 的访问也不是。

clang 的错误更有帮助

implicit use of 'this' pointer is only allowed within the
    evaluation of a call to a 'constexpr' member function

引用:

N3690 5.19/2 (emphasis added)

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

this, except in a constexpr function or a constexpr constructor that is being evaluated as part of e;

通过类型名调用静态成员函数是可行的

constexpr int m = T::getN();

关于c++ - GCC 4.9 constexpr 错误的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27946241/

相关文章:

c++ - 在派生类的构造函数中初始化没有默认构造函数的基类

c++ - 是否在目标平台上评估了 constexpr?

c++ - constexpr 函数内的非文字(通过 std::is_constant_evaluated)

c++ - 静态 constexpr 全局变量

c++ - G++ 中的匿名仿函数?

c++ - 遍历多个命令行参数

c++ - 多集 STL 中的下界

c++ - 从 std::array 获取对原始数组的引用

c++ - 如何找到函数的多个定义

c++ - G++ 4.5 错误 : No diagnostic for narrowing in initializer list