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

标签 c++ function dictionary stdmap

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

标题:

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)();

注意:如果您只处理无效构造函数,您甚至可以仅插入 &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/

相关文章:

python - 在嵌套字典和列表中查找所有出现的键

r - 将 ggplot map 与 coord_equal() 对齐

返回 mysql_fetch_assoc() 的 PHP 函数会导致基于索引的数组?

c++ - 如何对 std::map 中的部分键进行二进制搜索?

c++ - 循环 C++ 头文件包括

C++11 Variadic Templates : 3. .n int's separated into first, middle, last

javascript - 函数使用的内存被删除后会发生什么

c++函数在f()+ g()中的调用顺序

c++ - 将空源文件添加到 STATIC 库的原因?

C++ 虚拟方法 : access rights, friends & Co