2

I have the following piece of code which represents an actual bigger piece of code:

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

Compiling with g++ -o main main.cpp -std=c++11 and GCC/G++ 4.8.3 the expected output is received: B created: 2

However, with GCC/G++ 4.9.1 the code does not compile, output:

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();
               ^

This is caused by a known bug in GCC 4.9: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59937 and in this older thread https://gcc.gnu.org/ml/gcc-bugs/2013-11/msg00067.html the usage of extern is proposed as a workaround. However, I am not able to get this workaround working.

Could you guys help me to make this code compile in GCC 4.9? Thank you!

4

1 回答 1

3

由于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(强调)

条件表达式 e 是核心常量表达式,除非按照抽象机的规则对 e 的求值将求值以下表达式之一:

this,除了在作为 e 的一部分计算的 constexpr 函数或 constexpr 构造函数中;

通过类型名调用静态成员函数有效

constexpr int m = T::getN();
于 2015-01-14T15:19:48.580 回答