问题描述
基本上在下面我想看看是否可以绕过使用 auto
关键字
Basically in below I want to see if I can get around having to use auto
keyword
我们有下面的代码[使用g ++ 4.9.2(Ubuntu 4.9.2-10ubuntu13)& clang version 3.6.0]:
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++ -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;
}
如何指定 code>而不是在声明/定义点使用
auto
关键字?我尝试了 create< int> :: test v = create< int>();
,但这不起作用。
How can I specify the type of v
rather than using theauto
keyword at its point of declaration/definition? I tried create<int>::test v = create<int>();
but this does not work.
ps
1)这不同于我在 即使代码是相同的
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
2)我不要在函数外定义类。
2)I do not want to define the class outside the function.
推荐答案
实际类型是隐藏的,因为它在函数内部是局部的,所以你不能明确地使用它。但您应该能够使用 decltype
,如
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(create<int>()) v = create<int>();
我没有看到这样的原因,但 / code>工程。
I fail to see a reason to do like this though, when auto
works.
这篇关于如何指定返回类的constexpr函数的类型(不使用auto关键字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!