I'm trying to make classes that follow a pattern, but trying to avoid using inheritance to solve the problem. But there is some common code that can be pulled into it's own class which can be reused. Like this:
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);
Is there any way to achieve what I want without writing this biolerplate code?
int A::foo() { return common.foo(); }
int B::foo() { return common.foo(); }