为 std::map 生成唯一键

generate unique key for std::map

本文关键字:唯一 一键 map std      更新时间:2023-10-16

>我有一个以字符串为键并存储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 ),但您当然可以定义您想要的方式)。

如果您决定存储"指向函数的指针",您将遇到同样的问题。你必须知道签名!没有什么不同。