如何为std :: vector <T>专门化模板成员函数

tun*_*2fs 24 c++ templates

我需要以两种不同的方式定义get方法.一个用于简单类型T.一个用于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));
    ...
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能为std :: vector专门化这个方法.因为代码应该看起来像这样:

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;    
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何专门为此功能.非常感谢.

Naw*_*waz 27

不要专门化功能模板.

相反,使用过载.

编写一个函数模板get_impl来处理一般情况,并重载(不专门)这个来处理特定的情况,然后调用get_implfrom get:

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) );
}
Run Code Online (Sandbox Code Playgroud)

这是实际的实现.

//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
}
Run Code Online (Sandbox Code Playgroud)

static_cast<T*>(0)get只是来澄清对呼叫一个棘手的方式.static_cast<T*>(0)is 的类型T*,并将其作为第二个参数传递给get_impl将帮助编译器选择正确的版本get_impl.如果T不是std::vector,将选择第一个版本,否则将选择第二个版本.