【问题标题】:Returning a class from a constexpr function requires virtual keyword with g++从 constexpr 函数返回一个类需要带有 g++ 的 virtual 关键字
【发布时间】:2015-12-24 17:11:13
【问题描述】:

您好,以下程序适用于 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++)?

【问题讨论】:

  • 程序使用recent version of g++ 编译得很好。宽松的 C++14 constexpr 函数规则在 gcc >= 5 中实现,请参阅gcc.gnu.org/projects/cxx1y.html 在此之前,您不能在 constexpr 函数中声明类。当getvirtual 时缺少诊断具有误导性。

标签: c++ g++ c++14 constexpr g++4.9


【解决方案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;
}

【讨论】:

  • 谢谢,但不幸的是,这不是我想要为我的特定工作案例做事的方式。
  • “函数内部定义的类不能在函数外部访问。” 这是不正确的,因为 C++14 的返回类型推导(或 C++11 的宽松返回类型推导)对于 lambdas)。
  • @Andrey Nasonov 请参阅stackoverflow.com/questions/32806835/…,了解我想要达到的目标的更详细说明。
  • g++ 4.9.2 支持这个吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2022-01-23
  • 2013-09-09
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多