[英]How can I specialize a template member function for std::vector<T>
我需要以兩種不同的方式定義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));
...
}
我怎樣才能為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;
}
但我不知道如何專門為此功能。 非常感謝。
不要專門化功能模板。
相反,使用過載。
編寫一個函數模板get_impl
來處理一般情況,並重載 (不特殊 )這個來處理特定的情況,然后從get
調用get_impl
:
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) );
}
這是實際的實現。
//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
}
get
的static_cast<T*>(0)
只是消除歧義歧義的一種棘手方法。 static_cast<T*>(0)
是T*
,並將其作為第二個參數傳遞給get_impl
將幫助編譯器選擇正確的get_impl
版本。 如果T
不是std::vector
,將選擇第一個版本,否則將選擇第二個版本。
呃。 稱之為別的什么? 例如
template<typename T>
const T& Parameters::getVector(const std::string& key)
{
Map::iterator i = params_.find(key);
std::vector<std::string> temp = boost::get<std::vector<std::string> >(i->second)
// T is already a vector
T ret; ret.reserve(temp.size());
for(int i=0; i<temp.size(); i++){
ret.push_back(boost::lexical_cast<typename T::value_type>(temp[i]));
}
return ret;
}
你必須稱之為:
foo.getVector<std::vector<int> > ("some_key");
您的問題中沒有任何內容排除這一點。
現在,如果你真的需要使用get()
,那么你必須依賴於部分特化結構,因為語言不支持函數部分特化。
這要復雜得多,例如:
template <typename T>
struct getter
{
const T& operator()(std::string const& key)
{
// default operations
}
};
// Should double check this syntax
template <typename T>
struct getter<std::vector<T, std::allocator<T> > >
{
typedef std::vector<T, std::allocator<T> > VecT;
const VecT& operator()(std::string const& key)
{
// operations for vector
}
};
然后在你的方法成為:
template<typename T>
const T& Parameters::get(const std::string& key)
{
return getter<T>()(key); // pass the structures getter needs?
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.