在C++11中,由于有一个标准std::to_string(),我对枚举类和其他小型数据类进行了函数重载,其中实现具有意义。
我的问题是,你实现了与
某种类型的
我的问题是,你实现了与
std::to_string()
相对应的什么?某种类型的
from_string()
(不存在于std中),或者你在类中实现了更合适的标准接口?std::to_string()
相对应的什么?from_string()
(不存在于std中),或者你在类中实现了更合适的标准接口?std::string to_string( int value );
you have
int std::stoi(std::string);
请点击这里。
http://zh.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
enum_ = boost::lexical_cast<my_enum>(my_str);
std::stoi
和其他函数只是C++对C库atoi
函数的包装。我认为他想要的更多是针对他自定义对象的插入和提取运算符。 - AJG85C++11为算术类型提供了stoi
、stol
、stod
等函数。
std::atoi(s.c_str())
(或 std::atol
或 std::atof
),这些函数在 C++03 中就已经存在了,以达到相同的效果。 - Frerich Raabe据我所知,C++11标准库只有stoi
等函数可以实现这个功能。但是如果您愿意使用boost(我认为它是C++的准标准库),则可以使用boost::lexical_cast
。为了让它工作,您只需要为您自己的类定义流运算符operator>>
和operator<<
(用于转换为字符串)的std::istream
(std::ostream
)。
即使不使用boost
,我仍然会使用流运算符来实现此功能,因此要从字符串中获取整数,我会执行以下操作:
std::string s = ...;
int i;
std::stringstream stream(s);
stream>>i;
当然,你可以将它放入更通用的函数中,这将为你提供类似于boost::lexical_cast
的功能。
<<
和>>
,以便使用字符串流(boost::lexical_cast)执行字符串转换。 - UncleBens