Reputation: 25
I have some data sets of known types that I'd like to convert into stl containers by specifying the desired types like this:
Dataset dataset0(....);
Dataset dataset1(....);
Dataset dataset2(....);
int i = dataset0.convert<int>();
vector<int> vi = dataset1.convert<vector<int> >();
pair<vector<bool>, pair<bool, float> > complex = dataset2.convert<vector<pair<vector<bool>, pair<bool, float> >> >();
therefor I have made the following function in my Dataset class:
class Dataset
{
....
template<typename T>
T convert();
};
It's trivial to implement for the basic types like this:
template<>
int convert<int>()
{
return int(/*implementation*/);
}
But the question is, how can I do this for stl containers of any type. Something like this:
template<>
vector<T> convert<vector<T> >() // ?? does not compile. where would T come from?
{
vector<T> ret;
for(/* Loop determined from data */)
{
ret .push_back(convert<T>())
}
return ret;
}
Upvotes: 1
Views: 175
Reputation: 120049
One would be tempted to simply say
template<typename T>
vector<T> convert<vector<T> >()
This however would mean that you are trying to define a partial specialization of a function template. This is not allowed in C++.
There's no easy work around. The only advice I can give is naming different variants of convert
differently (convert_to_vector
etc). If you wish to keep naming consistency, you can define a class template Convertor
and specialize it for different types, using different convertor functions. For instance:
class Dataset
{
template<typename T>
T convert();
template<typename T>
vector<T> convert_to_vector() { return vector<T>(); }
template<typename T>
list<T> convert_to_list() { return list<T>(); }
};
template<>
int Dataset::convert<int>() { return 0; }
template<>
double Dataset::convert<double>() { return 0; }
template <typename T> class Convertor
{
public: T convert (Dataset& d) { return d.convert<int>(); }
};
template <typename T> class Convertor< vector<T> >
{
public: vector<T> convert (Dataset& d) { return d.convert_to_vector<T>(); }
};
template <typename T> class Convertor< list<T> >
{
public: list<T> convert (Dataset& d) { return d.convert_to_list<T>(); }
};
Then use it like Convertor<some-type>.convert(data)
.
Upvotes: 2
Reputation: 26333
Maybe this would do
template<typename T>
vector<T> convert();
if you mentionned vector
as an example and want to use other type of containers also, then you should define a `container_type convert_to_container_type()' method for each of them
Upvotes: 0