在c++中不能在工厂模式中使用map

Cannot use map in factory pattern using c++

本文关键字:map 工厂 c++ 不能 模式      更新时间:2023-10-16

我试图为一个项目创建一个基本类型包装器,我想使用一个工厂来根据用户输入创建类型。

为了说明这一点,下面是布尔类型 的代码
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初始化器功能。