在c++中不能在工厂模式中使用map
Cannot use map in factory pattern using c++
我试图为一个项目创建一个基本类型包装器,我想使用一个工厂来根据用户输入创建类型。
为了说明这一点,下面是布尔类型 的代码class TypeBoolean :public GenericTypeWrapper<bool>, public ITypeWrapper
{
public:
TypeBoolean(bool b = false)
{
this->setValue(b);
}
std::string getTypeName()
{
return "Boolean";
}
static ITypeWrapper* __stdcall Create(){ return new TypeBoolean(); }
};
GenericTypeWrapper只是一个getter和setter的类而ITypeWrapper类只是一个抽象类里面有getTypeName函数
现在我的问题是工厂
using createTypeFunction = std::function<ITypeWrapper*(void)>;
class TypeFactory
{
private:
static std::map<std::string, createTypeFunction> creationFunctions;
TypeFactory()
{
std::vector<std::string> listOfTypeNames = { "Boolean" };
std::vector<createTypeFunction> listOfCreateFunctions = { TypeBoolean::Create() };
for (unsigned int i = 0; i < listOfTypeNames.size(); i++)
{
creationFunctions.insert(listOfTypeNames[i], listOfCreateFunctions[i]);
}
}
};
现在显然有更多的类型,但问题也只出现在一个类型上。在
这一行出现错误creationFunctions.insert(listOfTypeNames[i], listOfCreateFunctions[i]);
错误状态:
error C2664: 'void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::initializer_list<std::pair<const _Kty,_Ty>>)' : cannot convert argument 1 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>>'
我不明白为什么我得到这个错误抛出,所以欢迎任何建议
方法map::insert
不接受key和value,只接受iterator和value_type。
试试这行:
creationFunctions[listOfTypeNames[i]] = listOfCreateFunctions[i];
你确定这行编译时没有警告吗?
std::vector<createTypeFunction> listOfCreateFunctions = { TypeBoolean::Create() };
对我来说看起来很可疑,我本以为是&TypeBoolean::Create
,但可能是我错过了一些新的c++ 11初始化器功能。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 使用一个考虑到std::map中键值的滚动或换行的键
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 使用Unique_ptr确保工厂中的对象唯一
- 带有继承的C++工厂
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 使用字符数组作为 Map 中的键
- C++如何创建 std::map
- C++ equivalent to Java Map getOrDefault?
- 从其他容器中移动构造"std::map"
- 在c++中不能在工厂模式中使用map