gpt4 book ai didi

c++ - C++ 中的对象工厂字典

转载 作者:搜寻专家 更新时间:2023-10-31 01:32:48 24 4
gpt4 key购买 nike

我需要实现一个静态映射,使我能够在给定字符串的情况下检索新对象:

标题:

static const map<string, function<void(MyObject)>> Dictionary;

来源:

const map<string, function<void(MyObject)>> * const ObjectDictionary = boost::assign::map_list_of
("Car", new MyCarObject())
("Ship", new MyShipObject());

但是我在编译时遇到了问题:

'<function-style-cast>': cannot convert from 'initializer list' to 'std::pair<const char *,MyCarObject *>'

我也不确定这个工厂的用途。

如何在 C++ 中实现此行为?


注意:我正在尝试做的是将我过去所做的一些代码从 C# 移植到 C++:

public static class MyFactory
{

public static readonly Dictionary<string, Func<MyObject>> ObjectDictionary = new Dictionary<string, Func<MyObject>>()
{
["Car"] = () => new MyCarObject(),
["Ship"] = () => new MyShipObject(),
};

}

所以我可以读取文本文件并创建给定字符串的对象:

var getObject = default(Func<MyObject>);

CurrentObjectDictionary.TryGetvalue(objectName, out getObject);

if(getObject != null)
{
MyObject = getObject();
//MyObject.Data = ...
//store
}

最佳答案

您可以直接使用创建者函数初始化 map ,无需 boost 往返。

    const std::map<std::string, std::function<unique_ptr<Object>()>> dict{
{"car", [](){ return std::make_unique<MyCarObject>();}},
{"ship", [](){ return std::make_unique<MyShipObject>();}}
};

http://cpp.sh/5uzjq

用法:

auto vehicle = dict.at(vehicle_type)();

注意:如果您只处理 nullary 构造函数,您甚至可以只插入 &std::make_unique<T>进入 map :

const map<...> dict{
{"car", &std::make_unique<Car>},
{"ship", &std::make_unique<Ship>}
};

关于c++ - C++ 中的对象工厂字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42528962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com