在同一个类中使用constexpr作为模板形参出错
Error using a constexpr as a template parameter within the same class
如果我尝试编译以下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函数的求值,所以你的测试用例都不能在那里工作。)
我有一个类似的错误与以下代码:
struct Test{
struct Sub{constexpr Sub(int i){}};
static constexpr Sub s=0;
};
在gcc 4.7.1中"error: 'constexpr Test::Sub::Sub(int)'在常量表达式中被调用"而这将成功编译:
struct Sub{constexpr Sub(int i){}};
struct Test{
static constexpr Sub s=0;
};
相关文章:
- 使用mem_fun_ref if成员函数需要多个形参
- 通过类的模板形参特化成员模板结构
- 非类型引用形参/实参
- 哪个模板形参在boost::shared_ptr构造函数中使用一个原始指针
- 如何确保迭代器模板形参与模板类的模板形参具有相同的数据类型
- 如何在编译时通过模板形参默认值的名称/指针获取函数的类型
- c++:候选模板被忽略:模板形参显式指定的参数无效
- c++中作为形参的指针
- 哪种方法更适合为函数提供编译时间常数?函数实参与模板形参
- 包含void*结构的函数的Const正确性和形参
- 传递boost::函数,该函数接受一个模板实参作为默认为NULL的形参
- 将右值引用形参强制转换为右值引用
- 给引用形参赋值使对象无效
- 当实参是初始化列表而形参是引用时,重载解析
- const整型模板形参的条件
- 使用作为模板形参提供的基类成员,不带限定符
- 模板类的不同返回类型取决于类的形参
- 模板形参有二义性:无法推断模板实参
- 是否有必要在定义中使用模板形参来引用同一个类?
- 在同一个类中使用constexpr作为模板形参出错