C ++:数据类型是函数的map的语法? [英] C++: Syntax for map where Data type is function?

查看:141
本文介绍了C ++:数据类型是函数的map的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我想要的是这样的:

  IDictionary< string,action()> dict = new Dictionary< string,action()>(); 

如何在C ++中执行此操作?这给编译器带来了错误:

  map< string,void()>练习; 


解决方案

使用 boost :: function ,这是一个多态包装器, (包括函数,函数对象等)。

  map< string,function< void()>> ; ...; 

请注意,新的C ++标准已包含函数 < functional>






背景:C ++中这种类型的内置机制是旧的C风格函数指针( void(*)())。这些都是非常低级的,基本上只是存储函数的内存地址,因此远不及C#代表的强大功能。



你不能创建匿名函数,既不能引用特定对象的成员函数,也不能引用任何变量或数据(闭包)。

因此,通常使用所谓的函数,它们是通过重载运算符()来模仿函数行为的类。与模板结合使用时,可以使用普通的函数指针。



问题是这些函数通常由不能被引用的特殊或匿名类型组成
$ b $ 函数是解决所有问题的最酷方式 - 所有行为都像一个函数,包括很酷的新lambda样式表达式。

  function< void()> f = [](){cout<< 你好,世界> }; 
f();


In C#, what I want would look something like this:

IDictionary<string, action()> dict = new Dictionary<string, action()>();

How do I do this in C++? This gives compiler errors:

map<string, void()> exercises;

解决方案

Use boost::function, a polymorphous wrapper for any object that can be called with your signature (including functions, function objects etc).

map<string, function<void()>> ...;

Note that the new C++ standard has already included function in <functional>.


To explain the backgrounds: The only builtin mechanism of this kind in C++ are old C-style function pointers (void (*)()). These are extremely low-level, basically just storing the memory address of a function, and therefore far from even coming close to the power of C#'s delegates.

You can't create anonymous functions, neither can you refer to a particular object's member functions or any variables or data (closures).

Thus, one often utilizes so called functors which are classes that mimic the behaviour of a function by overloading the operator (). In combination with templates, they are used whereever ordinary function pointers can be used.

The problem is that these functors often consist of peculiar or anonymous types that can't be referred to conveniently.

The function is the coolest way to address them all - Everything that behaves like a function, including cool new lambda-style expressions.

function<void()> f = []() { cout << "Hello, World"> };
f();

这篇关于C ++:数据类型是函数的map的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆