Hi the following program works with g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13) but the virtual
keyword is required for the function get
:
//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;
}
If I omit the virtual
keyword, I get the following error :
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
}
^
How can I get the code above to work (with g++) without having to use the virtual
keyword?
Classes defined inside a function cannot be accessed outside the function.
My suggestion are: declare test
outside the function and add const
qualifier to get
function.
#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;
}
来源:https://stackoverflow.com/questions/32806405/returning-a-class-from-a-constexpr-function-requires-virtual-keyword-with-g