I have a templated c++ class which acts on containers. In the class implementation I need access to the type of the data the container contains. I've currently defined it like this:
template <typename ContainerType, typename DataType>
class MyClass {
DataType a;
DataType foo(DataVector& vec, DataType s);
};
And when I instantiate it I instantiate it like this
MyClass< vector<float>, float > c1;
MyClass< CustomVector<double>, double > c2;
MyClass< Lib::ContainerFloat, Lib::Float > c3;
This works, but is there a way of doing this without duplicating the type info (i.e. float, double etc)? I.e. use some decltype-like magic to get the contained data type. So I'd like to be able to instantiate with:
MyClass< vector<float> > c1;
MyClass< CustomVector<double> > c2;
MyClass< Lib::ContainerFloat > c3;
and declare the class with:
template <typename ContainerType>
class MyClass {
// get DataType automatically from ContainerType
DataType a;
DataType foo(DataVector& vec, DataType s);
};
As a concept, all containers are expected to support value_type
as a type. See http://en.cppreference.com/w/cpp/concept/Container.
Last I checked, value_type
is supported by:
std::vector
std::list
std::set
std::multiset
std::unordered_set
std::unordered_multiset
std::queue
std::array
std::map
std::unordered_map
std::unordered_multimap
std::multimap
std::stack
std::priority_queue
I think it's safe for you to use:
template <typename ContainerType>
class MyClass {
using DataType = ContainerType::value_type;
};
MyClass< vector<float>> c1;
If DataType
can ever be different than ContainerType::value_type
, it will be better to use (Thanks are due to @AlexeyAndronov for the suggestion):
template <typename ContainerType,
typename DataType = ContainerType::value_type>
class MyClass {
};