如果我尝试编译以下 C++0x 代码,我会收到一个错误:
template<int n> struct foo { };
struct bar {
static constexpr int number() { return 256; }
void function(foo<number()> &);
};
对于 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’
使用 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.
如果我将 constexpr
函数移动到基类,它可以在 gcc 上运行,并在 clang 上给出相同的错误消息:
template<int n> struct foo { };
struct base {
static constexpr int number() { return 256; }
};
struct bar : base {
void function(foo<number()> &);
};
代码是否错误,或者它是 gcc 4.6 对 C++0x 实现的限制或错误?如果代码错了,为什么错了,C++11标准的哪些条款说错了?
最佳答案
在 C++ 中,类的成员函数的内联定义仅在类中的每个声明都被解析后才被解析。因此,在您的第一个示例中,编译器无法在声明 function()
的位置看到 number()
的定义。
(没有已发布的 clang 版本支持评估 constexpr 函数,因此您的所有测试用例都不能在那里工作。)
关于c++ - 在同一类中使用 constexpr 作为模板参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8108314/