您好下面的程序可與G ++ 4.9.2(Ubuntu的4.9.2-10ubuntu13),但是是所必需的功能的get
關鍵字virtual
虛擬關鍵字:從constexpr函數返回一個類需要使用g ++
//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 ++)工作?
程序編譯細帶有[最新版本克++的](http://melpon.org/wandbox/permlink/MYiV0wciN8hWmhAM)。輕鬆的C++ 14 constexpr函數規則在gcc> = 5中實現,請參閱https://gcc.gnu.org/projects/cxx1y.html在此之前,您無法在constexpr函數中聲明類。 'get'是'虛擬'時缺少診斷是誤導性的。 – dyp