我想用原始类型(int
,float
,double
)和向量类型(vector<int>
,vector<float>
,vector<double>
)对函数进行模板化。下面是我的代码。我想知道在构建不同的向量案例时是否有一种方法可以减少代码重复的模板parseKeyValue()
。谢谢!
#include <iostream>
#include <typeinfo>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
template<class T> T parseKeyValue(stringstream& ss){
T value;
while(ss >> value){};
return value;
}
template<> vector<string> parseKeyValue(stringstream& ss){
vector<string> value;
string item;
while(ss >> item) value.push_back(item);
return value;
}
template<> vector<int> parseKeyValue(stringstream& ss){
vector<int> value;
int item;
while(ss >> item) value.push_back(item);
return value;
}
template<typename T>
ostream& operator<<(ostream& os, const vector<T>& v){
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " "));
return os;
}
int main(){
stringstream ss("1-2-3 7-8-9");
vector<string> t = parseKeyValue< vector<string> >(ss);
cout << t << endl;
stringstream ss2("123 789");
vector<int> t2 = parseKeyValue< vector<int> >(ss2);
cout << t2 << endl;
stringstream ss3("123 789");
int t3 = parseKeyValue< int >(ss3);
cout << t3 << endl;
return 0;
}
您可以将其包装在一个类模板中,该模板可以是部分专用的。
您定义函数的方式,您需要对函数进行部分专业化,这在C ++中是不合法的。即使was