Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c++ - How can I specialize a template member function for std::vector<T>

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...