@DanielLangr @luxun @cdhowie 对于 XY 问题感到抱歉。我不确定我能解释清楚,但我尽力了。情况几乎是这样的:有一个基础对象“Worker”和一些子对象。Chef\xe3\x80\x81tailor...孩子们的动作和walk\xe3\x80\x81run\xe3\x80\x81sleep...一样,但是技能不同,厨师可以做食物,裁缝可以做衣服。Invoker 调用 Worker dothings 但并不确切知道他们的职业。所以我在 Worker 的基础对象上添加了一个接口 dothings(Thing)。Thing 是一个枚举,值为 MakeFood\xe3\x80\x81MakeClothes...
\n\nWorker *w = new Chef();\nw->dothings(MakeFood);//\nw->dothings(MakeClothes);//throw exception "w do not have skill"\nRun Code Online (Sandbox Code Playgroud)\n\n所以我认为也许可以在儿童中使用一个容器来描述它可以做什么以及如何做。
\n\n希望我解释清楚。还有更好的解决方案吗?
\n\n我想将不同的 lambda 表达式放入列表或 Qmap 中,如下所示。
\n\nQmap<String, lambda> map;\nmap.insert("first",[](int i) -> int {return i;});\nmap.insert("second",[](string s) -> string {return s;});\nRun Code Online (Sandbox Code Playgroud)\n\n在C++中可以吗?lambda 的类型是什么?
\nabh*_*ora 10
这是可能的,但使用函数包装器。
例如,
std::map<std::string, std::function<void(std::string)>> my_map;
my_map.emplace("first", [](std::string i) { std::cout << i << std::endl; });
Run Code Online (Sandbox Code Playgroud)
但是,如果您想将任何类型的参数传递给函数并从 lambda/函数返回任何类型,请使用boost::any。如果您使用的是std::any或以上版本,您也可以使用std::any C++17。
编辑:
一个工作示例:
#include <iostream>
#include <string>
#include <functional>
#include <map>
#include <boost/any.hpp>
int main()
{
auto any = [](boost::any i)
{
std::cout << "In any" << std::endl;
if (i.type() == typeid(int))
std::cout << boost::any_cast<int>(i) << std::endl;
return boost::any(1000);
};
std::map<std::string, std::function<boost::any(boost::any)>> my_map;
my_map.emplace("first", any);
my_map.emplace("second", [](boost::any i) -> boost::any { });
auto ret = my_map["first"](100);
std::cout << boost::any_cast<int>(ret) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
In any
100
1000
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14212 次 |
| 最近记录: |