解析类型名称(Parsing type names)

编程入门 行业动态 更新时间:2024-10-23 03:15:45
解析类型名称(Parsing type names)

假设我有一个字符串,例如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); ... 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...

最满意答案

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"

本文发布于:2023-07-15 18:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117534.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   类型   Parsing   type   names

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!