Don't specialize function template.
Instead, use overload.
Write a function template get_impl
to handle the general case, and overload (not specialize) this to handle the specific case, then call get_impl
from get
as:
template<typename T>
const T& Parameters::get(const std::string& key)
{
//read the explanation at the bottom for the second argument!
return get_impl(key, static_cast<T*>(0) );
}
And here goes the actual implementations.
//general case
template<typename T>
const T& Parameters::get_impl(const std::string& key, T*)
{
Map::iterator i = params_.find(key);
return boost::lexical_cast<T>(boost::get<std::string>(i->second));
}
//this is overload - not specialization
template<typename T>
const std::vector<T>& Parameters::get_impl(const std::string& key, std::vector<T> *)
{
//vector specific code
}
The static_cast<T*>(0)
in get
is just a tricky way to disambiguate the call. The type of static_cast<T*>(0)
is T*
, and passing it as second argument to get_impl
will help compiler to choose the correct version of get_impl
. If T
is not std::vector
, the first version will be chosen, otherwise the second version will be chosen.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…