Runtime Polymorphism with std::variant

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật