[英]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.