C++ 描述如何使用来简化变量定义
c++ decltype how to use to simplify variable definition
比如说,我在我的一个类中有这段代码,它定义了
- 键的映射和另一个映射
- 第二个映射是另一个键和一个函数处理程序
- 函数处理程序是一个需要 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
。 - 如果要从函数返回此类型的值,请使用
auto
或decltype
。 - 如果要获取结构/类成员的类型,请使用
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
相关文章:
- 用C++中的一个变量定义一个常量
- 变量定义到C++布尔值转换
- 未声明的标识符错误,但变量定义正确 (?)
- C++多线程程序:变量定义为类成员的隔离错误
- 将变量定义为静态时,为什么可以多次定义它
- 初始值设定项列表与构造函数赋值与变量定义
- 如何根据传递给函数的变量定义特征矩阵大小
- C++ 描述如何使用来简化变量定义
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 是否修改其声明语句中的变量定义良好
- 使用类的其他成员变量定义类的成员变量数组
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 元组 std::get() 不适用于变量定义的常量
- 全局使用变量定义和C 声明
- C++变量定义中的易失性类型量词位置
- 将变量定义为数组和正确的语法
- 多个,包括具有变量定义的头文件
- 调用构造函数,并将成员作为参数解析为变量定义
- 逗号分隔变量定义中关系前的序列
- 如何使用命名变量定义常量右值引用参数的默认值