Returning a class from a constexpr function requires virtual keyword with g++

浪尽此生 提交于 2019-12-08 02:14:58

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!