检查C++ 11中的字符串是否为T类型

Sla*_*zer 1 c++ string types

是否有标准库函数来检查字符串S是否为T类型,因此可以转换为T类型的变量?

我知道有一个istringstream STL类可以使用operator >>,用一个从字符串转换的值填充T类型的变量.但是,如果字符串内容没有类型T的格式,它将被填充无意义.

Ker*_* SB 6

正如@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)

用法:

请注意,这boost::lexical_cast基本上是一个更聪明的版本,声称非常有效(可能比我们在这里无条件地使用iostreams更多).