How to select a member variable with a type parameter?

I have a cache object that caches several different types of objects, as shown below:

class Cache
{
public:
    ObjectTable<ObjTypeA> m_objACache;
    ObjectTable<ObjTypeB> m_objBCache;
    ObjectTable<ObjTypeC> m_objCCache;
};

The (terrible) way that I am currently using the cache currently directly accesses the properties of the cache class "m_objACache" and "m_objBCache" as follows:

Cache c;
c.m_objACache.getObjectWithid(objectBuffer, 1);
c.m_objACache.getObjectWithid(objectBuffer, 2);
c.m_objBCache.getObjectWithid(objectBuffer, 3);

etc..

What I would like to do is something like this: -

class Cache
{
public:
    template <typename T>
    void getObjectWithId(T &objectBuffer, int id)
    {
        ObjectTable<T>.getObjectWithId(objectBuffer, id);
    }
};

But obviously this does not work, because when I have a " ObjectTable<T>", I need a variable name, but I can’t change the template class variables - can I do this? Or this will be the case if you declare all the variables and access it as follows:

class Cache
{
public:
    void getObjectWithId(ObjTypeA &objectBuffer, int id)
    {
        m_objACache.getObjectWithId(objectBuffer, id);
    }

    void getObjectWithId(ObjTypeB &objectBuffer, int id)
    {
        m_objBCache.getObjectWithId(objectBuffer, id);
    }

    void getObjectWithId(ObjTypeC &objectBuffer, int id)
    {
        m_objCCache.getObjectWithId(objectBuffer, id);
    }

protected:
    ObjectTable<ObjTypeA> m_objACache;
    ObjectTable<ObjTypeB> m_objBCache;
    ObjectTable<ObjTypeC> m_objCCache;
};

Which seems very verbose.

, ObjectTable, , - , downcasting, , .

!

+3
2

?

class Cache
{
 // An "envelope" type which up-casts to the right ObjectTable<T> 
 // if we have a type parameter T. 
 struct ObjectTables : ObjectTable<ObjTypeA>,  
                       ObjectTable<ObjTypeB>, 
                       ObjectTable<ObjTypeC> {};

 ObjectTables tables; 
public:

    template <typename T>
    void getObjectWithId(T &objectBuffer, int id)
    { 
        // C++ does the work here
        ObjectTable<T> &o=tables;
        t.getObjectWithId(objectBuffer, id);
    }
};

, . ObjectTables < > , .

+6

Boost.Fusion boost::fusion::map.

, - , - .

:

boost::fusion::map< std::pair<Key1,Value1> > map;
Value1& v = boost::fusion::at<Key1>(map);
0

Source: https://habr.com/ru/post/1758346/


All Articles