【发布时间】:2013-06-30 13:37:58
【问题描述】:
我的问题不是我不能映射到函数指针,而是相反。
使用我当前的设置,我可以通过字符串实例化类。 现在,我正在尝试从类类型中获取字符串。
我提出的方法:
class A {};
template <typename T> T* create(void) { return new T; }
static std::map<std::string,A*(*)(void)> str_to_class;
static std::map<A*(*)(void),std::string> class_to_str;
template <typename T> void Bind(std::string identity) {
// T must inherit from A.
str_to_class[identity]=&create<T>;
class_to_str[&create<T>]=identity;
}
A* MakeFromString(std::string identity) {
return str_to_class[identity](); // Compiles fine.
}
template <typename T> std::string GetTypeString(void) {
return class_to_str[&create<T>]; // Error!
}
int main(int,char**) {
Bind<A>("A");
A* new_entity=CreateFromString("A");
}
Error: C2679: binary '[' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
我知道我可以使用 dynamic_cast 来检查实体类型,但这需要为每个要使用的类编写代码。
【问题讨论】:
-
template<typename T> create()声明/定义在哪里? -
哎呀,“构造”和“创造”混淆了。固定。
-
尝试为这个问题创建一个SSCCE——你给出的代码不完整,当你填写不完整的部分时,它编译/工作正常...
标签: c++ map function-pointers