简化命名类型的 C++ 语言功能(特别是在函数声明中)
C++ language feature to simplify naming types (especially in function declarations)
我想知道 C++ 中是否有宏或语言元素表示与函数中的 return 值相同的类型。
例如:
std::vector<int> Myclass::CountToThree() const
{
std::vector<int> col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
是否有某种语言元素而不是第 std::vector<int> col;
行?
我知道这很琐碎,但我只是厌倦了输入它 ;-)。
你可以做两件事:
Type aliasing,using
或 typedef
。
typedef std::vector<int> IntVector;
using IntVector = std::vector<int>;
这两个声明是等价的,并且提供了另一个名称,编译器将其视为原始名称的同义词。它也可以用于模板。
为什么是两种表示法,而不是一种? using
关键字在 C++11 to simplify notation for typedefs in templates.
中提供
在 C++14 中,您可以使用 auto
关键字进行自动 return 类型推导:
auto Myclass::CountToThree() const
{
std::vector<int> col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
有关更广泛的解释,请参阅 this related question。
对于你的例子,你可以只写
std::vector<int> Myclass::CountToThree() const
{
return {1,2,3};
}
通常,您可以使用 decltype
获得 return 类型的函数,但这可能对您的情况没有帮助:
std::vector<int> Myclass::CountToThree() const
{
decltype( CountToThree() ) col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
我想知道 C++ 中是否有宏或语言元素表示与函数中的 return 值相同的类型。
例如:
std::vector<int> Myclass::CountToThree() const
{
std::vector<int> col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
是否有某种语言元素而不是第 std::vector<int> col;
行?
我知道这很琐碎,但我只是厌倦了输入它 ;-)。
你可以做两件事:
Type aliasing,
using
或typedef
。typedef std::vector<int> IntVector; using IntVector = std::vector<int>;
这两个声明是等价的,并且提供了另一个名称,编译器将其视为原始名称的同义词。它也可以用于模板。
为什么是两种表示法,而不是一种?
using
关键字在 C++11 to simplify notation for typedefs in templates. 中提供
在 C++14 中,您可以使用
auto
关键字进行自动 return 类型推导:auto Myclass::CountToThree() const { std::vector<int> col; col.push_back(1); col.push_back(2); col.push_back(3); return col; }
有关更广泛的解释,请参阅 this related question。
对于你的例子,你可以只写
std::vector<int> Myclass::CountToThree() const
{
return {1,2,3};
}
通常,您可以使用 decltype
获得 return 类型的函数,但这可能对您的情况没有帮助:
std::vector<int> Myclass::CountToThree() const
{
decltype( CountToThree() ) col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}