mardi 18 septembre 2018

Getting struct dynamically from map given key value pairs

I have two very similar classes A and B. They have the same methods and everything. The only difference is those methods take very similar but different struct parameters. Unfortunately, I don't have access to those class A and B and cannot modify them. What I am trying to do is combine those classes and depending on the arguments given (for example A and enable), I want to extract a_command_enable out of the map. I tried using boost::variant and I believe I am not using it correctly. Below is the sample working code.

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

using namespace std; 

struct a_command_enable { string name; }; 
struct a_command_disable { string key; }; 

struct b_command_enable { string name; };
struct b_command_disable { string key; };

class A { 
    void send_enable(a_command_enable*); 
    void send_disable(a_command_disable*); 
}; 

class B { 
    void send_enable(a_command_enable*); 
    void send_disable(a_command_disable*); 
};

template<typename T> 
class C {
    public:
    T t; 
    C() { 
        t = T();
    }

    struct a_command_enable aenable; 
    struct a_command_disable adisable; 
    struct b_command_enable benable; 
    struct b_command_disable bdisable; 

    typedef boost::variant< 
        a_command_enable,
        a_command_disable,
        b_command_enable,
        b_command_disable
    > mCommands; 

    map<pair<string, string>, mCommands> command_map = { 
        { make_pair("A", "enable"), aenable }, 
        { make_pair("A", "disable"), adisable }, 
        { make_pair("B", "enable"), benable }, 
        { make_pair("B", "disable"), bdisable }
    };


    void send_command(string class_name, string action) { 
        mCommands command = command_map[make_pair(class_name, action)];
        // send_enable(command); // can't call this because mCommands is variant
        /** get struct dynamically from map **/
    }

    // writing boost apply visitor for all of the commands? 
    struct visitor1 : public boost::static_visitor<a_command_enable> { 
        public: 
            a_command_enable operator()(a_command_enable a) const { return a; }
    };
};

int main() { 
    C<A> a; 
    a.send_command("A", "enable"); 
    // a.send_command<a_command_enable>("A", "enable"); // right now added template for send_command and calling like this

    C<B> b;
    b.send_command("B", "disable"); 
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire