dimanche 3 avril 2016

Access members of different type within templates c++

I try to write a template to set different types of values into different member -maps of a class like this:

class Properties
{
    map<string, string> descriptions;
    map<string, string> propMap_string;
    map<string, int32_t> propMap_int32_t;
    map<string, tm> propMap_tm;

public:

    Properties();
    ~Properties();


    template <typename T>
    void initProperty(string name, const T a_value, string description)
    {
        valueMap_T[name] = a_value;
        descriptions[name] = description;
    }
};

This, of course does not compile.

The only solution to this I have found so far is this. But it seems unessecary complicated to me

class Properties
{
    map<string, string> descriptions;
    map<string, string> propMap_string;
    map<string, int32_t> propMap_int32_t;
    map<string, tm> propMap_tm;

    //dummyValue is not used, it is jus thtere to make the template work
    map<string, string>* getMap(string dummyValue) 
    { 
        // getting rid of compiler warnings
        (void)dummyValue; 
        return &propMap_string; 
    }
    map<string, int32_t>* getMap(int32_t dummyValue)  
    { 
        (void)dummyValue; 
        return &propMap_int32_t; 
    }
    map<string, tm>* getMap(tm dummyValue) 
    { 
        (void)dummyValue; return &propMap_tm; 
    }

public:

    Properties();
    ~Properties();

    template <typename T>
    void initProperty(string name, const T a_value, string description)
    {
        map<string, T>* valueMap = getMap(a_value);
        valueMap->at(name) = a_value;
        descriptions[name] = description;
    }

};

Does maybe someone know to make that work without this getter-workaround?

I would prefers some "template"-style fashion, like it was emphasized in my first, non-compiling piece of code

I have stumbled over similar problems in the past, so maybe I am just overlooking something ... maybe something new -> c++11 or c++14 ??

Aucun commentaire:

Enregistrer un commentaire