samedi 30 décembre 2017

Boost variant get underlying value

Is there a way to make the following work avoiding inheritance?

A and B share the same API, all I want to do is to obtain the underlying value and call on that the common member function.

#include <iostream>
#include <cstdlib>
#include <boost/variant.hpp>

struct A {
    void foo(){
        std::cout << "A" << std::endl;
    }
};
struct B {
    void foo(){
            std::cout << "B" << std::endl;
    }
};

template <typename Ret>
Ret getUnderlying(auto t) {
    switch (t.which()){
        case 0: return boost::get<A>(t);
        case 1: return boost::get<B>(t);
    }   
}

int main()
{
    using AB = boost::variant<A,B>;
    AB var;
    var = A();
    getUnderlying(var).foo();

}

http://ift.tt/2CcxLKk

Aucun commentaire:

Enregistrer un commentaire