提问者:小点点

强制派生类重写一组虚函数之一


给定一个具有一些虚函数的基类,有人能想出一种方法来强制派生类在编译时重写一组虚函数中的一个吗?或者是实现相同目标的类层次结构的另一种提法?

代码中:

struct Base
{
    // Some imaginary syntax to indicate the following are a "pure override set"
    // [
    virtual void function1(int) = 0;
    virtual void function2(float) = 0;
    // ...
    // ]
};

struct Derived1 : Base {}; // ERROR not implemented
struct Derived2 : Base { void function1(int) override; }; // OK
struct Derived3 : Base { void function2(float) override; }; // OK

struct Derived4 : Base // ERROR too many implemented
{
    void function1(int) override;
    void function2(float) override;
};

我不确定我真的有一个实际的用例,但是当我实现一些松散地遵循这个模式的东西时,我想到了这个问题,并且认为这是一个有趣的问题,需要思考。


共2个答案

匿名用户

不,但你可以假装。

Base具有非虚拟的float和int方法,这些方法转发到纯虚拟的std变体。

两个助手类,一个int一个float,实现了std变体1,将这两种情况转发给纯虚拟int或float实现。

它负责处理“错误类型”案件。

从一个或另一个helper派生inherit,并仅实现int或float。

struct Base
{
    void function1(int x) { vfunction(x); }
    void function2(float x) { vfunction(x); }
    virtual void vfunction(std::variant<int,float>) = 0;
};
struct Helper1:Base {
    void vfunction(std::variant<int,float> v) final {
      if (std::holds_alternative<int>(v))
        function1_impl( std::get<int>(v) );
    }
    virtual void function1_impl(int x) = 0;
};
struct Helper2:Base {
    void vfunction(std::variant<int,float> v) final {
      if (std::holds_alternative<float>(v))
        function2_impl( std::get<float>(v) );
    }
    virtual void function2_impl(float x) = 0;
};

struct Derived1 : Base {}; // ERROR not implemented
struct Derived2 : Helper1 { void function1_impl(int) override; }; // OK
struct Derived3 : Helper2 { void function2_impl(float) override; }; // OK

这使用https://en.wikipedia.org/wiki/non-virtual_interface_pattern--接口包含非虚拟方法,可以重写这些方法的详细信息以使它们的行为不同。

如果您担心人们会重写vfunction,您可以使用私有锁技术,或者只给它起一个类似private_implementation_detail_do_not_implement的名字,并信任您的代码审查过程。

匿名用户

如果不重写所有抽象的虚拟方法,您的类将保持抽象。如果要实例化对象,您必须执行所有这些操作。