How to achieve runtime polymorphism with std::variant
with same multiple(50) methods defined across multiple classes. This the my code
#include <iostream>
#include <variant>
class Derived1 {
public:
void method1() const {
std::cout << "calling derived1 method1!" << std::endl;
}
void method2() const {
std::cout << "calling derived1 method2!" << std::endl;
}
void method3() const {
std::cout << "calling derived1 method3!" << std::endl;
}
};
class Derived2 {
public:
void method1() const {
std::cout << "calling derived2 method1!" << std::endl;
}
void method2() const {
std::cout << "calling derived2 method2!" << std::endl;
}
void method3() const {
std::cout << "calling derived2 method3!" << std::endl;
}
};
struct CallMethod1 {
void operator()(const Derived1& d1) { d1.method1(); }
void operator()(const Derived2& d2) { d2.method1(); }
};
struct CallMethod2 {
void operator()(const Derived1& d1) { d1.method2(); }
void operator()(const Derived2& d2) { d2.method2(); }
};
struct CallMethod3 {
void operator()(const Derived1& d1) { d1.method3(); }
void operator()(const Derived2& d2) { d2.method3(); }
};
int main() {
std::variant<Derived1, Derived2> var{};
std::visit(CallMethod1{}, var);
std::visit(CallMethod2{}, var);
std::visit(CallMethod3{}, var);
}
But the above design doesn’t scale well, for every method I need to have a separate visitor CallMethodN
and a call operator overload method for each of the classes. Can I do something like variant_variable.method_name(arguments_list)
.
5
The closest you can get is using auto
#include <iostream>
#include <variant>
class Derived1 {
public:
void method1() const {
std::cout << "calling derived1 method1!" << std::endl;
}
void method2() const {
std::cout << "calling derived1 method2!" << std::endl;
}
void method3() const {
std::cout << "calling derived1 method3!" << std::endl;
}
};
class Derived2 {
public:
void method1() const {
std::cout << "calling derived2 method1!" << std::endl;
}
void method2() const {
std::cout << "calling derived2 method2!" << std::endl;
}
void method3() const {
std::cout << "calling derived2 method3!" << std::endl;
}
};
int main() {
std::variant<Derived1, Derived2> var{};
std::visit([](auto&& obj) { obj.method1(); }, var);
std::visit([](auto&& obj) { obj.method2(); }, var);
std::visit([](auto&& obj) { obj.method3(); }, var);
}
making named classes instead of using lambdas could reduce the object code size, but it has no other perceivable difference, and you need the functions to be defined in the header to use auto
anyway.
You could acheive your goal of variant_object.function_name(params)
by wrapping the variant in a struct, and using the lambdas internally.
struct MyCustomVariant
{
std::variant<Derived1, Derived2> var;
decltype(auto) method1()
{
return std::visit([](auto&& obj) ->decltype(auto) { return obj.method1(); }, var);
}
decltype(auto) method2()
{
return std::visit([](auto&& obj) ->decltype(auto) { return obj.method2(); }, var);
}
decltype(auto) method3()
{
return std::visit([](auto&& obj) ->decltype(auto) { return obj.method3(); }, var);
}
};
int main() {
MyCustomVariant var{};
var.method1();
var.method2();
var.method3();
}
note: ->decltype(auto)
is needed if you return references, but if you return void
you can omit it (lambdas return auto
by default so they return a copy, not the reference)
Passing arguments is a bit tricky because you will need to pass them by forwarding reference if you don’t want to change their value category, but you could have a more strongly-typed interface if you can give up on the value-category of the arguments.
decltype(auto) method1(int& arg)
{
return std::visit([&](auto&& obj) ->decltype(auto) { return obj.method1(arg); }, var);
}
Compared to
template <typename...Args>
decltype(auto) method1(Args&&...args)
{
return std::visit([&](auto&& obj) ->decltype(auto) { return obj.method1(std::forward<Args>(args)...); }, var);
}
The main advantage of the first version is that it produces human-readable errors if the user plugs in a wrong argument, the second version produces a wall of substitution failures.
And don’t forget that you can use macros to reduce the boilerplate.
If you want runtime polymorphism you might as well use runtime polymorphism 🙂
This would be my take on this.
#include <iostream>
#include <memory>
class Derived1
{
public:
void method1() const
{
std::cout << "calling derived1 method1!" << std::endl;
}
void method2() const
{
std::cout << "calling derived1 method2!" << std::endl;
}
void method3() const
{
std::cout << "calling derived1 method3!" << std::endl;
}
};
class Derived2
{
public:
void method1() const
{
std::cout << "calling derived2 method1!" << std::endl;
}
void method2() const
{
std::cout << "calling derived2 method2!" << std::endl;
}
void method3() const
{
std::cout << "calling derived2 method3!" << std::endl;
}
};
class MyInterface
{
public:
virtual ~MyInterface() = default;
virtual void method1() const = 0;
virtual void method2() const = 0;
virtual void method3() const = 0;
};
template <typename T>
class MyInterfaceImpl : public MyInterface
{
public:
// forward all arguments to the constructor of the implementation if needed
template <typename... Args>
MyInterfaceImpl(Args&&... args) :
m_impl(std::forward<Args>(args)...)
{
}
MyInterfaceImpl() = default;
~MyInterfaceImpl() override = default;
void method1() const override
{
m_impl.method1();
}
void method2() const override
{
m_impl.method2();
}
void method3() const override
{
m_impl.method3();
}
private:
T m_impl;
};
// if needed you can make template specialization for MyInterfaceImpl
// for classes that are not completely implementing all methods (or use slightly different function names)
int main()
{
// Runtime polymorphism in action
std::unique_ptr<MyInterface> d1 = std::make_unique<MyInterfaceImpl<Derived1>>();
std::unique_ptr<MyInterface> d2 = std::make_unique<MyInterfaceImpl<Derived2>>();
d1->method1();
d1->method3();
d2->method2();
d2->method3();
return 0;
}
2