Hello, everyone! This might seem an easy question to you, and I wouldn't even post it if it wasn't for my love of clean code. So here goes:
What I want to do is read some pairs of values from a file, one on a line; for example, I might have a file that looks like this:
Code:
john
7
paul
3
luke
15
or like this:
Code:
ridley scott
alien
stanley cubrick
odyssey 2001
steven spielberg
independence day
Now I thought I can write one function to read them all, using templates:
Code:
template<int>
int convert(char * buf)
{
return atoi(buf);
}
template<string>
string convert(char * buf)
{
return string(buf);
}
template<class T1, class T2>
vector<pair<T1, T2> > load_vector(ifstream & f)
{
vector<pair<T1, T2> > v;
pair<T1, T2> p;
char buf[128];
while(!f.eof())
{
f.getline(buf, sizeof(buf));
p.first = convert<T1>(buf);
f.getline(buf, sizeof(buf));
p.second = convert<T2>(buf);
if(!p.first.empty())
{
v.push_back(p);
}
}
return v;
}
and I would call (say) load_vector<string, int> and get a nicely structured vector.
Not.
The compiler generates an error message, along the lines of
'convert' : invalid template argument for 'function-parameter', compile-time evaluatable constant expression expected
, which I don't really understand. Isn't <string, int> constant enough? MSDN didn't help, either.
Thank you for your time