如何指定返回 class 的 constexpr 函数的类型(不求助于 auto 关键字)
How to specify type of a constexpr function returning a class (without resorting to auto keyword)
基本上在下面我想看看我是否可以绕过必须使用 auto
关键字
假设我们有以下代码[适用于 g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13) & clang 版本 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;
}
如何指定 v
的类型而不是使用
auto
关键字在 declaration/definition 点?我试过 create<int>::test v = create<int>();
但这不起作用。
p.s。
1) 这与我在 Returning a class from a constexpr function requires virtual keyword with g++ 提出的问题不同,即使代码相同
2)我不想在函数外定义class。
实际类型是隐藏的,因为它在函数内部是局部的,因此您不能显式使用它。但是,您应该能够像
那样使用 decltype
decltype(create<int>()) v = create<int>();
虽然 auto
有效,但我看不出这样做的理由。
基本上在下面我想看看我是否可以绕过必须使用 auto
关键字
假设我们有以下代码[适用于 g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13) & clang 版本 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;
}
如何指定 v
的类型而不是使用
auto
关键字在 declaration/definition 点?我试过 create<int>::test v = create<int>();
但这不起作用。
p.s。
1) 这与我在 Returning a class from a constexpr function requires virtual keyword with g++ 提出的问题不同,即使代码相同
2)我不想在函数外定义class。
实际类型是隐藏的,因为它在函数内部是局部的,因此您不能显式使用它。但是,您应该能够像
那样使用decltype
decltype(create<int>()) v = create<int>();
虽然 auto
有效,但我看不出这样做的理由。