0

Let's say I've got a string such as string values = "hello 2 88.9 true" which holds several values of different types. I have several variables which were declared with the appropriate types (here a string, an int, a float and a bool). What I basically want to do is this :

field0 = getValue(0,values);
field1 = getValue(1,values);
... etc

So what I want is a getValue whose return type matches the type of the corresponding field. Is this possible with simply templates ? I feel like you cannot just specify the return type you want to use without having the template type in the parameters of the template function. The body of the function itself is probably going to use boost's lexical_cast and a stringstream but if you have a better solution, I'm up for that as well !

I'm new to templates so I would very much appreciate an explanation...

4

2 回答 2

0

我会这样做:

#include <sstream>
...
std::stringstream ss;
ss << values;
ss >> field0 >> field1 >> field2 >> field3;

如果我真的想要它作为一个getValue函数,我可能会以粗略但有效的方式来做:

template<typename T>
void getValue(unsigned int n, string str, T &val)
{
  string junk;
  std::stringstream ss(str);
  for(unsigned int k=0; k<n; ++k)
    ss >> junk;
  ss >> val;
  return;
}
于 2013-05-28T13:23:50.337 回答
0
using std::stringstream;
using std::string;

string a;
int b;
double c;
bool d;

string values = "hello 2 88.9 true";
stringstream in(values);
in >> a >> b >> c >> std::boolalpha >> d;
于 2013-05-28T13:26:01.523 回答