【发布时间】:2015-12-24 17:11:13
【问题描述】:
您好,以下程序适用于 g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13),但函数 get 需要 virtual 关键字:
//g++ -std=c++14 test.cpp
//test.cpp
#include <iostream>
using namespace std;
template<typename T>
constexpr auto create() {
class test {
public:
int i;
virtual int get(){
return 123;
}
} r;
return r;
}
auto v = create<int>();
int main(void){
cout<<v.get()<<endl;
}
如果我省略 virtual 关键字,我会收到以下错误:
test.cpp: In instantiation of ‘constexpr auto create() [with T = int]’:
test.cpp:18:22: required from here
test.cpp:16:1: error: body of constexpr function ‘constexpr auto create() [with T = int]’ not a return-statement
}
^
如何在不使用virtual 关键字的情况下使上述代码正常工作(使用g++)?
【问题讨论】:
-
程序使用recent version of g++ 编译得很好。宽松的 C++14 constexpr 函数规则在 gcc >= 5 中实现,请参阅gcc.gnu.org/projects/cxx1y.html 在此之前,您不能在 constexpr 函数中声明类。当
get是virtual时缺少诊断具有误导性。
标签: c++ g++ c++14 constexpr g++4.9