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.
For your example, you could just write
std::vector<int> Myclass::CountToThree() const
{
return {1,2,3};
}
In general, you can get the return type of a function with decltype
, but this probably doesn't help in your situation:
std::vector<int> Myclass::CountToThree() const
{
decltype( CountToThree() ) col;
col.push_back(1);
col.push_back(2);
col.push_back(3);
return col;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With