指定std::to_string()的补充

Specifying a complement to std::to_string()?

本文关键字:string std to 指定      更新时间:2023-10-16

在c++ 11中,因为有一个标准的std::to_string(),我为枚举类和其他小数据类重载了这个函数,在这些情况下实现是有意义的。

我的问题是,作为std::to_string()的补充,你实现了什么?

某种from_string()(在std中不存在),或者在您的类中实现更合适的标准接口?

标准使用的是旧c语言中使用的简洁命名方案,所以当你有

std::string to_string( int value );
你有

int std::stoi(std::string);

看到

http://en.cppreference.com/w/cpp/string/basic_string/stol

所以你可能有。

std::string to_string(my_enum);

你可能有

my_enum stomy_enum(std::string)

尽管我只是在啰嗦

my_enum string_to_my_enum(std::string)

或者直接使用流

std::stringstream ss(my_str);
if(ss >> emun_) //conversion worked

定义流操作符还允许使用boost的词法强制转换;

enum_ = boost::lexical_cast<my_enum>(my_str);

c++ 11有stoi, stol, stod等算术类型

如果你的类型是一个类,那么以字符串作为参数的构造函数比自由函数更有意义。

据我所知,c++ 11标准库只有stoi等。但是,如果您可以使用boost(我认为它是c++的准标准库),则可以使用boost::lexical_cast。为此,您只需要为您自己的类分别定义流操作符operator>>operator<<(用于转换为字符串)和std::istream (std::ostream)。

当不使用boost时,我仍然会使用流操作符,所以要从字符串中获得int,我会做如下操作:

std::string s = ...;
int i;
std::stringstream stream(s);
stream>>i;

当然,您可以将其放入更通用的函数中,这将为您提供类似于boost::lexical_cast的功能。