简体   繁体   English

如何指定返回类的 constexpr 函数的类型(不使用 auto 关键字)

[英]How to specify type of a constexpr function returning a class (without resorting to auto keyword)

Basically in below I want to see if I can get around having to use auto keyword基本上在下面我想看看我是否可以绕过必须使用auto关键字

Suppose that we have the following piece of code [works with g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13) & clang version 3.6.0] :假设我们有以下代码段[适用于 g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13) & clang version 3.6.0]:

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

How can I specify the type of v rather than using the auto keyword at its point of declaration/definition?如何指定v的类型而不是在其声明/定义点使用auto关键字? I tried create<int>::test v = create<int>();我试过create<int>::test v = create<int>(); but this does not work.但这不起作用。

ps ps

1)this is different from the question that I was asking at Returning a class from a constexpr function requires virtual keyword with g++ even through the code is the same 1)这与我在Returning a class from a constexpr function requires virtual keyword with g++中提出的问题不同,即使代码相同

2)I do not want to define the class outside the function. 2)我不想定义函数外的类。

The actual type is hidden as it's local inside the function, so you can't explicitly use it.实际类型是隐藏的,因为它在函数内部是局部的,因此您不能显式使用它。 You should however be able to use decltype as in但是,您应该能够像这样使用decltype

decltype(create<int>()) v = create<int>();

I fail to see a reason to do like this though, when auto works.但是,当auto工作时,我看不到这样做的理由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法获得返回constexpr auto的函数类型 - Unable to get type of function returning constexpr auto 从constexpr函数返回类需要使用g ++虚拟关键字 - Returning a class from a constexpr function requires virtual keyword with g++ 使用静态constexpr成员函数返回类内部的auto - use of a static constexpr member function returning auto inside class 尝试传递constexpr lambda并使用它来显式指定返回类型 - Trying to pass a constexpr lambda and use it to explicitly specify returning type constexpr函数不返回constexpr值吗? - constexpr function not returning constexpr value? 如何不使用std :: function来存储函数对象? - How to store a function object without resorting to std::function? 如何在不诉诸依赖注入的情况下模拟遗留函数? - How to mock a legacy function without resorting to dependency injection? 将模板化的constexpr传递给函数来推断自动对象的类型 - Passing templated constexpr to function inferring type of auto object 如何在包含 static constexpr 的类型的概念的要求中指定返回类型? - how to specify the return type in a requirement for a concept for types that contains a static constexpr? constexpr类的全球类型 - constexpr global of class type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM