[英]Returning a class from a constexpr function requires virtual keyword with g++
嗨,以下程序適用於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 ++一起使用)?
在函數內部定義的類不能在函數外部訪問。 我的建議是:在函數外部聲明test
並添加const
限定符以get
函數。
#include <iostream>
using namespace std;
class test {
public:
int i;
int get() const {
return 123;
}
};
template<typename T>
constexpr test create() {
return test();
}
auto v = create<int>();
int main(void){
cout<<v.get()<<endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.