在同一个类中使用constexpr作为模板参数时出错

Ces*_*arB 6 c++ compiler-errors constexpr c++11

如果我尝试编译以下C++ 0x代码,我收到一个错误:

template<int n> struct foo { };

struct bar {
    static constexpr int number() { return 256; }

    void function(foo<number()> &);
};
Run Code Online (Sandbox Code Playgroud)

使用gcc 4.6.1,错误消息是:

test.cc:6:27: error: ‘static constexpr int bar::number()’ used before its definition
test.cc:6:28: note: in template argument for type ‘int’
Run Code Online (Sandbox Code Playgroud)

使用clang 2.8,错误消息是:

test.cc:6:20: error: non-type template argument of type 'int' is not an integral
      constant expression
        void function(foo<number()> &);
                          ^~~~~~~~
1 error generated.
Run Code Online (Sandbox Code Playgroud)

如果我将constexpr函数移动到基类,它适用于gcc,并在clang上给出相同的错误消息:

template<int n> struct foo { };

struct base {
    static constexpr int number() { return 256; }
};

struct bar : base {
    void function(foo<number()> &);
};
Run Code Online (Sandbox Code Playgroud)

代码是错误的,还是gcc 4.6的C++ 0x实现的限制或错误?如果代码错误,为什么它是错的,C++ 11标准的哪些条款说它不正确?

ser*_*rvn 5

在C++中,只有在解析类中的每个声明后才会解析类的成员函数的内联定义.因此,在您的第一个示例中,编译器无法number()function()声明的位置查看定义.

(没有发布的clang版本支持评估constexpr函数,所以你的测试用例都不会在那里工作.)