c++ - 按值传递的返回类型多态性

标签 c++ polymorphism

我不确定问题标题是否准确...让我先解释一下我最初的简单场景,然后继续解释我想做什么,但不能做什么。

最初,我有类似的东西:

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]());

到目前为止一切顺利(我认为)。但是,现在有几种派生的操作数类型,例如类 RegisterOperand:公共(public)操作数。我有新的专用 genOperand 函数,理想情况下会返回派生类型的实例。但我不能这样做:

Operand genOperandC() { ...; return RegisterOperand(); }

我不能这样做:

RegisterOperand genOperandC() { ...; return RegisterOperand(); }

static const OpGen generators[] = 
{
    ...
    genOperandC,
};

但是,我知道如果我要返回引用或指针类型,这会起作用,所以我目前唯一的选择是:

Operand *genOperandC() { ...; return new RegisterOperand(); }

现在需要显式清理,而这原本是不必要的。

有没有我没有考虑过的替代方案?

最佳答案

你可以换行:

class Operand
{
public:

private:
  std::unique_ptr<OperandImpl> mImpl;
};

这类似于策略模式:实际的操作数行为是隐藏的,并且可以通过非虚拟接口(interface)访问。用户得到一份Operand,她不需要了解它的内部就可以使用它,你可以自由地实现各种派生行为。

关于c++ - 按值传递的返回类型多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3082995/

相关文章:

c++ - 如何处理状态转换并将 "if"语句替换为多态类型?

c++ - 唯一指针和 3 法则

c# - 为什么将基类设置为等于派生类型仅在设置范围内起作用?

c++ - Posix 线程教程

c# - 托管 C dll 调用 C# dll,FileNotFoundException

machine-learning - liblbfgs 在 C++ 中编译

c++ - 在 C++ 中转换函数指针

c# - 为什么从 C# 调用 C++ COM 函数总是在主线程中执行?

C++:按位与

c++ - 具有派生成员函数指针的多态性?