I am wondering if there is a macro or language element in C++ that represents the same type as the return value in a function.
For example:
std::vector<int> Myclass::CountToThree() const
{
std::vector<int> col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
Instead of line std::vector<int> col;
is there some sort of language element?
I know it is pretty trivial but I am just bored with typing it ;-).
You can do two things:
Type aliasing, either using
or typedef
.
typedef std::vector<int> IntVector;
using IntVector = std::vector<int>;
These two declarations are equivalent, and provide another name that compiler treats as a synonym of the original name. It can be used for templates as well.
Why two notations, not just one? The using
keyword was provided in C++11 to simplify notation for typedefs in templates.
In C++14, you could use the auto
keyword for automatic return type deduction:
auto Myclass::CountToThree() const
{
std::vector<int> col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
For a broader explanation see this related question.