C++语言功能可简化命名类型(尤其是在函数声明中)
C++ language feature to simplify naming types (especially in function declarations)
我想知道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;
}
除了行std::vector<int> col;
,是否有某种语言元素?我知道这很微不足道,但我只是厌倦了打字;-)。
你可以做两件事:
-
类型别名,
using
或typedef
。typedef std::vector<int> IntVector; using IntVector = std::vector<int>;
这两个声明是等效的,并提供编译器视为原始名称同义词的另一个名称。它也可以用于模板。
为什么是两个符号,而不仅仅是一个符号?
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; }
有关更广泛的解释,请参阅此相关问题。
对于您的示例,您可以编写
std::vector<int> Myclass::CountToThree() const
{
return {1,2,3};
}
通常,您可以使用 decltype
获取函数的返回类型,但这在您的情况下可能没有帮助:
std::vector<int> Myclass::CountToThree() const
{
decltype( CountToThree() ) col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
相关文章:
- 为什么使用SFINAE而不是函数重载
- () 函子后面的括号,而不是函数指针?
- 在这种情况下,如何传递成员函数而不是函数?
- 如何读取指针的值,因为这个指针是函数的返回?
- " sizeof "操作员在编程中真的很重要吗,尤其是在构建大型应用程序时?
- 如何使用boost::hana::unpack和构造函数,而不是函数
- 如何将从第 2 个字符开始的字符串作为函数中的参数传递以进行递归,并约束数据 tiee 是函数中的字符串?
- 如何删除新分配的字符,这也是函数返回值?
- GCC5:嵌套变量模板不是函数模板?
- 插入向量时,使用lambda的返回而不是函数的返回是否有意义?
- 为什么只有指向函数的指针而不是函数的变量?
- 为什么这不是函数模板的部分专业化
- 是函数本地静态默认或价值初始化
- 显式专用化"..."不是函数模板的专用化
- 从结构中获取所有可变参数模板类型,该结构是函数模板中的类型参数
- QWebEngineView立即崩溃,尤其是在滚动后 - Qt5.8
- C++语言功能可简化命名类型(尤其是在函数声明中)
- C++理解模板的确切语义,尤其是函数参数
- 定义参数包扩展的"pattern",尤其是在函数调用中
- 内联在gcc中的行为:虚拟函数的内联,尤其是在我的例子中的析构函数