我不确定问题标题是否准确......让我先解释一下我原来的简单场景,然后继续解释我想做什么,但不能.
最初,我有类似的东西:
class Operand;
Operand genOperandA() { ...; return Operand(); }
Operand genOperandB() { ...; return Operand(); }
... // more operand-generation functions
typedef Operand (*OpGen)();
// Table of function pointers
static const OpGen generators[] =
{
genOperandA,
genOperandB,
...
};
// Function to do some operation on the operand
void operate(Operand& op);
...
// Example call
operate(generators[1]());
Run Code Online (Sandbox Code Playgroud)
到目前为止这么好(我想).但是,现在有几种派生的操作数类型,例如class RegisterOperand : public Operand.我有新的专用genOperand函数,理想情况下会返回派生类型的实例.但我不能这样做:
Operand genOperandC() { ...; return RegisterOperand(); }
Run Code Online (Sandbox Code Playgroud)
我不能这样做:
RegisterOperand genOperandC() { ...; return …Run Code Online (Sandbox Code Playgroud)