这是一段代码:
class Class
{
static constexpr int getBug();
};
constexpr int Class::getBug()
{
return 0;
}
我基本上做的是在类声明中声明一个static
constepxr
方法,然后我实现它。
原始代码被拆分成两个文件,包含更多的方法/属性被剥离,只留下需要的代码。
当我编译代码时,我从 GCC 4.6.0 得到以下错误:
Class.cpp:6:29: internal compiler error: in merge_types, at cp/typeck.c:825
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://gcc.gnu.org/bugs.html> for instructions.
这真的是一个错误吗?
在那种情况下,我必须提供什么报告?
我已经在 online C++0x compiler 上测试了代码并得到以下错误:
prog.cpp:3:33: error: the 'constexpr' specifier cannot be used in a function declaration that is not a definition
prog.cpp:6:29: error: a constexpr function cannot be defined outside of its class
此编译器使用 GCC 4.5.1。 它让我知道我的代码格式错误,但引入了更多问题:
- 为什么 GCC 4.5.1 报错而 GCC 4.6.0 报告错误?
写完最后一段后,我在 GCC 4.6.0 上测试了剥离 static
关键字,单独的实现在没有任何警告的情况下编译!
- 为什么同一系列的两个编译器表现如此不同?
我知道 constexpr
方法应该避免任何不同于 return
的语句,这可能解释了 GCC 4.5.1 错误报告。
由于我的方法使用宏条件来返回良好的(常量)值,因此需要几行代码来解释为什么我要使用分离的实现(除了通常的建议之外)。
我的配置:
Mac OS X.7
GCC 4.6.0
Target: x86_64-apple-darwin10.7.0
Configured with: ./configure
COLLECT_GCC_OPTIONS='-mmacosx-version-min=10.7.0' '-v' '-save-temps' '-std=c++0x' '-c' '-shared-libgcc' '-mtune=core2'
最佳答案
这是因为 constexpr
是该语言的新特性,并且根据 C++0x Support in GCC页面,对这个特性的支持首先在 4.6 中添加到 GCC 中。我怀疑它实际上是编译器中的错误,可以在 4.6.1 或更高版本中修复。
GCC 4.5.2 会生成错误,因为该功能在该版本中尚不可用。事实上,如果您要检查 4.5.2 的标准库 header ,您会看到所有 constexpr
方法(按照标准规定)都说“需要 constexpr”。
关于c++ - 静态 constexpr 方法实现导致 gcc 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7700703/