C ++ language for simplifying name types (especially in function declarations)

I am wondering if in C ++ there is a macro or language element that represents the same type as the return value in the function.

For instance:

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;Is there some element of the language instead of the string ? I know this is pretty trivial, but I just get bored of it ,-).

+4
source share
2 answers

You can do two things:

  • Enter an alias , either or . using typedef

    typedef std::vector<int> IntVector;
    using IntVector = std::vector<int>;
    

    These two declarations are equivalent and provide a different name, which the compiler sees as a synonym for the original name. It can also be used for templates.

    , ? using ++ 11 typedefs .

  • ++ 14 auto :

    auto Myclass::CountToThree() const
    {
        std::vector<int> col;
        col.push_back(1);
        col.push_back(2);
        col.push_back(3);
        return col;
    }
    

    .

+6

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;
}
+2

All Articles