2014-10-16 52 views
0

大家好我想要使用此以下设置来创建一个类的实例:的std ::函数实例创建

class Interface 
{ 
     Interface(){} 
     virtual void init =0; 
}; 

class InstanceCreation 
{ 

void registerInstance(const std::string& name, std::function<Interface*(void)> interface) 
{ 
functionMap[name] = interface 
} 


Interface* getInstance(const std::string& name) 
{ 
Interface* temp; 
auto itor = functionMap.find(name); 
temp = itor->second; 

return temp; 
} 

std::map<std::string, std::function<Interface*(void)> > functionMap; 

}; 

这是失败,因为该行的编译:

temp = itor->second; 

错误描述未能在std::function<Interface*(void)>Instance*之间进行转换。我如何实现这种转换(静态,动态演员表不起作用)

作为后续问题,有没有人有任何想法如何使这项工作非空构造?

+0

第二个问题是没有意义的。此代码示例中没有任何内容与构造函数有关。 – clcto 2014-10-16 20:11:51

+1

等一下,我仔细看看,是'Instance'应该是'Interface'吗?编译器甚至允许行'virtual void init = 0;'? – clcto 2014-10-16 20:13:13

+0

这可能是我犯了一个错字,这是实际实现的简化版本 – Nark 2014-10-16 20:24:10

回答

4

要调用的函数,你加括号:

temp = itor->second(); 
+0

这是一个愚蠢的错误,这个问题的第二手仍然存在。 – Nark 2014-10-16 20:27:48

+0

@Nark我想你应该问一个新问题。目前,正如我在问题的评论中所说的,这个样本中没有任何东西与构造函数有关。 – clcto 2014-10-16 20:29:46