I need to define a get method in two different ways. One for simple types T. And once for std::vector.
template<typename T>
const T& Parameters::get(const std::string& key)
{
Map::iterator i = params_.find(key);
...
return boost::lexical_cast<T>(boost::get<std::string>(i->second));
...
}
How can I specialize this method for std::vector. As there the code should look something like this:
template<typename T>
const T& Parameters::get(const std::string& key)
{
Map::iterator i = params_.find(key);
std::vector<std::string> temp = boost::get<std::vector<std::string> >(i->second)
std::vector<T> ret(temp.size());
for(int i=0; i<temp.size(); i++){
ret[i]=boost::lexical_cast<T>(temp[i]);
}
return ret;
}
But I do not know how to specialize the function for this. Thanks a lot.
Don’t specialize function template.
Instead, use overload.
Write a function template
get_implto handle the general case, and overload (not specialize) this to handle the specific case, then callget_implfromgetas:And here goes the actual implementations.
The
static_cast<T*>(0)ingetis just a tricky way to disambiguate the call. The type ofstatic_cast<T*>(0)isT*, and passing it as second argument toget_implwill help compiler to choose the correct version ofget_impl. IfTis notstd::vector, the first version will be chosen, otherwise the second version will be chosen.