我需要以两种不同的方式定义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)
但我不知道如何专门为此功能.非常感谢.
我已经为字符串转换创建了一个小的实用程序函数,这样我就不必在整个地方创建ostringstream对象了
template<typename T>
inline string ToString(const T& x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion(string("ToString(") + typeid(x).name() + ")");
return o.str();
}
Run Code Online (Sandbox Code Playgroud)
我想为没有默认重载<< string for stringstream的实例(即std :: pair,std :: set,我自己的类)的实例提供此方法的一些特殊化,并且我遇到了模板的困难.我将用std :: pair示例说明,如果我想能够
string str = ToString(make_pair(3, 4));
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是为int定义显式特化
template<>
inline string ToString(const pair<int,int>& x)
{
std::ostringstream o;
if (!(o << "[" << x.first << "," << x.second << "]"))
throw BadConversion(string("ToString(pair<int,int>)"));
return o.str();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以为通用案例定义这个?
template<>
inline string ToString(const pair<T1,T2>& x)
{
std::ostringstream o;
if (!(o << "[" …Run Code Online (Sandbox Code Playgroud)