从constexpr函数返回一个类需要使用g ++的虚拟关键字 [英] Returning a class from a constexpr function requires virtual keyword with g++

查看:851
本文介绍了从constexpr函数返回一个类需要使用g ++的虚拟关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好下面的程序可以在g ++ 4.9.2(Ubuntu 4.9.2-10ubuntu13)下运行,但是函数 get需要 virtual 关键字

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
 }
 ^

如何获得上面的代码可以工作(使用g ++)而不必使用 virtual 关键字?

How can I get the code above to work (with g++) without having to use the virtual keyword?

推荐答案

在函数内定义的类不能在函数外部访问。
我的建议是:在函数之外声明 test 并将 const 限定符添加到获得函数。

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;
}

这篇关于从constexpr函数返回一个类需要使用g ++的虚拟关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆