转发函数调用成员变量

问题描述 投票:0回答:1

我试图使该遵循一个模式类,但尽量避免使用继承来解决这个问题。但是,是可以拉成它自己的类,它可以重复使用一些常用代码。像这样:

class Common {
    public:
        int foo() {return 1;}
};

class A {
    public:
        // Expose Common's public methods
        int bar() {return 2;}
    private:
        Common common;
};

class B {
    public:
        // Expose Common's public methods
        int bar() {return 3;}
    private:
        Common common;
};

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

std::variant<A, B> variant = A{};
std::visit(overloaded {
        [](A a) { a.foo(); },
        [](B b) { b.foo(); },
}, variant);

有没有什么方法可以达到我想要的东西没有写这个样板代码?

int A::foo() { return common.foo(); } 
int B::foo() { return common.foo(); } 
c++ c++17
1个回答
0
投票

你正在尝试实现通常称为混入。见What is a mixin, and why are they useful?

在C ++中,你通常是这样做:

  • 继承(没有动态调度)
  • CRTP

Two different mixin patterns in C++. (mixin? CRTP?)

还有其他不那么吸引人的解决方案:

  • 使common成员变量public或等同物(需要改变用户)
  • 宏,一个#include或任何类型的代码生成一个可扩展到任何你需要的接口
© www.soinside.com 2019 - 2024. All rights reserved.