是否有标准库函数来检查字符串S是否为T类型,因此可以转换为T类型的变量?
我知道有一个istringstream STL类可以使用operator >>,用一个从字符串转换的值填充T类型的变量.但是,如果字符串内容没有类型T的格式,它将被填充无意义.
正如@Cameron评论的那样,你可以做的最好是尝试失败:
#include <string>
#include <sstream>
#include <boost/optional.hpp>
template <typename T>
boost::optional<T> convert(std::string const & s)
{
T x;
std::istringstream iss(s);
if (iss >> x >> std::ws && iss.get() == EOF) { return x; }
return boost::none;
}
Run Code Online (Sandbox Code Playgroud)
或者,没有提升:
template <typename T>
bool convert(std::string const & s, T & x)
{
std::istringstream iss(s);
return iss >> x >> std::ws && iss.get() == EOF;
}
Run Code Online (Sandbox Code Playgroud)
用法:
第一版:
if (auto x = convert<int>(s))
{
std::cout << "Read value: " << x.get() << std::endl;
}
else
{
std::cout << "Invalid string\n";
}
Run Code Online (Sandbox Code Playgroud)第二版:
{
int x;
if (convert<int>(s, x))
{
std::cout << "Read value: " << x << std::endl;
}
else
{
std::cout << "Invalid string\n";
}
}
Run Code Online (Sandbox Code Playgroud)请注意,这boost::lexical_cast基本上是一个更聪明的版本,声称非常有效(可能比我们在这里无条件地使用iostreams更多).