C++ 描述如何使用来简化变量定义

c++ decltype how to use to simplify variable definition

本文关键字:变量 定义 描述 何使用 C++      更新时间:2023-10-16

比如说,我在我的一个类中有这段代码,它定义了

  • 键的映射和另一个映射
  • 第二个映射是另一个键和一个函数处理程序
  • 函数处理程序是一个需要 2 个参数的签名

现在,定义变量的签名看起来令人难以置信。

std::map<std::string, std::map<std::string,
std::function<void(std::shared_ptr<HTTPRequest>,
std::shared_ptr<HTTPResponse>)>>> routeFunctions_;

我最近开始了解decltype,但无法正确使用它。

decltype(x) routeFunctions_;  // What should be there in the place of x ?
如果您
  • 经常声明此类型的变量,请使用此类型的typedef
  • 如果要从函数返回此类型的值,请使用autodecltype
  • 如果要获取结构/类成员的类型,请使用decltype

看看这篇文章:

http://en.cppreference.com/w/cpp/language/auto http://en.cppreference.com/w/cpp/language/decltype

http://www.cprogramming.com/c++11/c++11-auto-decltype-return-value-after-function.html

在这种情况下,您的选择是typedef

typedef std::map<std::string, std::map<std::string,
std::function<void(std::shared_ptr<HTTPRequest>,
std::shared_ptr<HTTPResponse>)>>> RouteFunctionsContainer;
RouteFunctionsContainer routeFunctions_;

你在那里放了一个变量名,它与你想要的新变量的类型相同。

int x = 3;
decltype(x) y = 5; // y is an int because x is an int

您可以假装变量的类型在语法上替换为源代码中的 decltype。

直播: https://godbolt.org/g/6uzoJH