为 std::map 生成唯一键
generate unique key for std::map
>我有一个以字符串为键并存储lambda的映射。
到目前为止我已经尝试过
std::map <int, auto> callbackMap
并在没有相同数字的地方放一个 lambda。这可能吗?我不断收到错误,说函数不能将 auto 作为构造函数。
这是因为auto
只是一个编译时"功能",它将您需要的类型转换为非常定义的类型!您可能会将其与"变体"类型混淆...它不是这样工作的。
auto X = 3;
这并不意味着X
是"变体"。这就像编译器将其转换为:
int X = 3;
因此,请注意,X
有一个非常定义的类型。
您可以在映射中存储函数(lambda 是运算符),没问题。但是你的std::function<...>
非常明确。例:
std::map< int, std::function< int( int ) > > callbackMap;
callbackMap[ 0 ] = std::function< int( int ) >( [] ( int a ) { return a + 1; } );
callbackMap[ 1 ] = std::function< int( int ) >( [] ( int a ) { return a - 1; } );
callbackMap[ 2 ] = std::function< int( int ) >( [] ( int a ) { return a * 2; } );
callbackMap[ 3 ] = std::function< int( int ) >( [] ( int a ) { return a / 2; } );
请注意,您仍然需要知道函数的签名...(在我的示例中int( int a )
,但您当然可以定义您想要的方式)。
如果您决定存储"指向函数的指针",您将遇到同样的问题。你必须知道签名!没有什么不同。
相关文章:
- 容器,其中每个项可以有多个非唯一键 (c++17)
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 在unordered_multimap中精确迭代一次每个键的有效方法
- 如何从一组具有从左到右优先级的整数值创建有序整数键?
- 字数统计函数在将单词添加到一组唯一单词时遇到问题
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- 如何使用推力将相同键从一个数组复制到另一个数组的值
- 合并带有唯一键的Hushtables成一个C
- 寻求具有非唯一键或值的双向图
- 使用shared_ptr获得唯一所有权(有点)——这是一种好的做法吗
- set 如何与唯一键一起工作,但在C++中具有等效的键值
- 用于插入 std::unordered_set 的 3D 间坐标的唯一键
- 使用 GLFW 一次处理多个键输入
- 具有唯一键的多映射
- C++ 如何在具有 O(n) 遍历的不同映射容器中区分具有带值的重复键和具有值的唯一键的 Multimap
- 如何创建Google+Plus一键,同时已经使用GooglePlay游戏服务SDK for C++实现了排行榜
- 一键构建所有配置和平台
- c++是唯一一种使用mpi的语言吗
- 使用批处理文件使用 Cmake & Msbuild (vs2010) 一键构建我的项目
- QML - 一键锁定/解锁屏幕方向(安卓和最终的 ios)