c++ - 从 constexpr 函数返回一个类需要使用 g++ 的 virtual 关键字

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

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

最佳答案

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

#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++ - 从 constexpr 函数返回一个类需要使用 g++ 的 virtual 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806405/

相关文章:

c++ - 在 Linux 上使用控制台编译 C++ 时出现问题

c++ - 更新 C++ 时行为的无声变化是什么?

c++ - 当返回类型是 vector 容器时,是否有在 c++ 中返回 Null 的解决方法?

c++ - .*、->* 和 .-> 在 C++ 中是什么意思?

java - 从 Java (GCJ) 调用 C++ 代码

c++ - std::bind 和 std::weak_ptr

c++ - 维护ABI : adding constructor to struct

c++ - 来自二维数组的特征图

c++ - 类成员上的 Decltype 作为模板参数

c++ - 使用模板模板参数时的默认模板参数