Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ language feature to simplify naming types (especially in function declarations)

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 ;-).

like image 404
Richy Avatar asked Feb 07 '23 23:02

Richy


2 Answers

You can do two things:

  1. 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.

  2. 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.

like image 51
LookAheadAtYourTypes Avatar answered Feb 09 '23 12:02

LookAheadAtYourTypes


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;
}
like image 33
Jens Avatar answered Feb 09 '23 12:02

Jens