Для возврата класса из функции constexpr требуется виртуальное ключевое слово с g++

Привет следующая программа работает с g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13), но virtual ключевое слово требуется для функции 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;
}

Если я опущу 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
 }
 ^

Как я могу получить приведенный выше код для работы (с g++) без использования virtual ключевое слово?

1 ответ

Классы, определенные внутри функции, не могут быть доступны вне функции. Мое предложение: объявить 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;
}
Другие вопросы по тегам