C++语言功能可简化命名类型(尤其是在函数声明中)

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

本文关键字:尤其是 函数 声明 类型 功能 语言 可简化 C++      更新时间:2023-10-16

我想知道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;,是否有某种语言元素?我知道这很微不足道,但我只是厌倦了打字;-)。

你可以做两件事:

  1. 类型别名,usingtypedef

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

    这两个声明是等效的,并提供编译器视为原始名称同义词的另一个名称。它也可以用于模板。

    为什么是两个符号,而不仅仅是一个符号?using 关键字在 C++11 中提供,以简化模板中 typedef 的表示法。

  2. 在 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;
}