介绍很长,问题在最后:
假设我有一个正在创建接口(interface)的基类
class base
{
public:
virtual ~base();
virtual void calc( int* variables ) = 0;
}
和一些完成工作的继承类(这里只显示了两个):
class add : public base
{
const int a, b, c;
public:
add( int a_, int b_, int c_ ) : a(a_), b(b_), c(c_) {}
void calc( int* variables )
{
variables[a] = variables[b] + variables[c];
}
}
class inc : public base
{
const int a;
public:
inc( int a_ ) : a(a_) {}
void calc( int* variables )
{
variables[a]++;
}
}
最后是一些使用此构造的代码:
base* task[2];
task[0] = new add( 0, 1, 2 );
task[1] = new inc( 3 );
int data[4];
/* ... */
for( int i = 0; i < 2; i++ )
task[i]->calc( data );
目前为止一切正常 - 但它在编译期间定义了我的任务。这应该通过解析输入文件更改为运行时。假设解析已经完成并且在 std::string
中变量 command
是对象类型(如 add
或 inc
)并且在 std::vector<int> params
中是构造函数的参数。
现在我可以有一长串
if( command.compare( "add" ) )
task[end] = new add( params[0], params[1], params[2] );
else if( command.compare( "inc" ) )
task[end] = new inc( params[0] );
else /... */
除了变得相当不可读之外,这只是一个线性搜索。所以本着Why switch statement cannot be applied on strings?的精神我想用 std::map
替换线性搜索(或 HashMap ...)。
经过这么长的介绍,我终于可以回答这个问题了:
我如何定义和填写 std::map
以便以这样一种方式存储对对象的引用(?),以便我可以根据该信息在对象上动态创建后期?
所以对于上面的代码,我想做一些最终看起来像这样的事情:
// define and fill
std::map< std::sting, ???? > lookup;
lookup["add"] = add;
lookup["inc"] = inc;
/* ... */
// use:
while( linesInConfigAvailable )
{
/* ... parse ... */
switch( params.size() )
{
case 1:
task[end] = new lookup[command]( params[0] );
break;
case 3:
task[end] = new lookup[command]( params[0], params[1], params[2] );
break;
}
}
PS:到目前为止,我的代码中不需要 RTTI。如果能一直这样就好了...
最佳答案
嗯,你不能。在 C++ 中,类不是对象,它们更像是一种抽象结构,只存在于编译器在编译时处理数据。
但是,您可以使用给定的签名创建所谓的工厂函数:
class A : public Base
{
public:
static Base* Create() { return new A; }
};
class B : public Base
{
public:
static Base* Create() { return new B; }
};
...
编辑:如果“创建”功能像这样统一,您当然可以制作模板。
然后,您可以在映射中存储函数指针:
typedef Base* (*FactoryType)();
std::map< std::string, FactoryType >
lookup["A"] = A::Create;
lookup["B"] = B::Create;
并恰本地称呼他们:
task[end] = lookup[command]();
关于c++ - 如何在 std::map 中存储 "object type"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12026003/