Invalid use of non-static member where member is const and list-initialised?

时间:2016-04-04 16:59:53

标签: c++ c++11

I have this header:

class A{
    const int x;
    typedef std::array<MyClass, x> ARRAY;   // Cannot use x here?

};

and in the implementation file:

A::A() : x(10) {}

but I get compiler errors for the typedef line saying:

invalid use of non-static data member A::x

I thought x only had to be const for use in the array sizing? I really wish to avoid static.

1 个答案:

答案 0 :(得分:3)

In order to use x as a non-type template parameter, it has to be a core constant expression - basically it has to be evaluatable at compile-time. A simple const is not sufficient criteria, const just means it is not modifiable in the future - it does not mean that it is a known quantity at compile-time.

There is one edge case here which may be causing some confusion in that a const integral is a core constant expression in cases like this:

const int x = 10;
std::array<int, x> arr; // ok

There's no reason to want to avoid static. You will want to do something like this:

struct A {
    static constexpr int x = 10;
    typedef std::array<MyClass, x> ARRAY;
};