FPGalero FPGalero - 1 month ago 6
C++ Question

C++ define a class member type according to its template

In our code we have the following class:

template<class A, class B>
class myClass
{
typedef std::list<Object<A,B>> MyList;
typedef std::map<A, typename mList::iterator> MyMap

MyList mList;
MyMap mMap;
}


class A is metaprogrammed and it can be a string, int and so on.
I would like to change the code so in case class A is a "meta string" a map will be used, otherwise unordered_map will be used.

I've tried to add some more meta programming but haven't succeeded yet:

template< class A, class B>
struct MapType // default
{
typedef std::list<Object<A,B>> MyList;
typedef std::unordered_map<A,B> MyMap;
}

//TODO struct with templated A (string) to use std::map

template<class A, class B>
class myClass
{
???? // if A ~ String define myMap to MAP . otherwise unordered

MyList mList;
MyMap mMap;
}


any other suggestions for using different map type will be appreciated as well.

Thanks

Answer

A simple solution would be to use std::conditional to check if A is the same as your "meta string" class (I picked std::string for demonstration purposes):

template<class A, class B>
class myClass
{
    std::list<Object<A,B>> mList;
    std::conditional_t<std::is_same<A,std::string>::value,
                       std::map<A,B>, std::unordered_map<A,B>> mMap;
};

Another possibility would be to use partial specialization:

template<class A, class B>
class myClass
{
    std::list<Object<A,B>> mList;
    std::unordered_map<A,B> mMap;
};

template<class B>
class myClass<std::string,B>
{
    std::list<Object<std::string,B>> mList;
    std::map<std::string,B> mMap;
};
Comments