假设我有一个字符串,例如string values = "hello 2 88.9 true" ,它包含几个不同类型的值。 我有几个变量用适当的类型声明(这里是一个字符串,一个int,一个浮点数和一个bool)。 我基本上想要做的是:
field0 = getValue(0,values); field1 = getValue(1,values); ... etc所以我想要的是一个getValue它的返回类型与相应字段的类型相匹配。 这可以用简单的模板吗? 我觉得你不能只指定你想要使用的返回类型,而不需要在模板函数的参数中使用模板类型。 函数本身可能会使用boost的lexical_cast和一个字符串流,但如果你有一个更好的解决方案,我也可以使用它!
我是模板的新手,所以我非常感谢解释......
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); ... etcSo 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...
最满意答案
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; 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;更多推荐
类型,模板,values,电脑培训,计算机培训,IT培训"/> <meta name="description"
发布评论