指定std::to_string()的补充
Specifying a complement to std::to_string()?
在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
的功能。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然