Ric*_*chy 4 c++ typedef auto c++11
我想知道在C++中是否有一个宏或语言元素表示与函数中的返回值相同的类型.
例如:
std::vector<int> Myclass::CountToThree() const
{
std::vector<int> col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
Run Code Online (Sandbox Code Playgroud)
而不是行std::vector<int> col;是否有某种语言元素?我知道这非常简单,但我只是厌倦了输入它;-).
你可以做两件事:
键入别名,using或者typedef.
typedef std::vector<int> IntVector;
using IntVector = std::vector<int>;
Run Code Online (Sandbox Code Playgroud)
这两个声明是等效的,并提供编译器将其视为原始名称的同义词的另一个名称.它也可以用于模板.
为什么有两个符号,而不仅仅是一个?该using关键字在C++ 11中提供,以简化模板中typedef的表示法.
在C++ 14中,您可以使用auto关键字进行自动返回类型扣除:
auto Myclass::CountToThree() const
{
std::vector<int> col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
Run Code Online (Sandbox Code Playgroud)
有关更广泛的解释,请参阅此相关问题.