【发布时间】:2017-06-16 02:19:23
【问题描述】:
我目前正在尝试实现我自己的标准输入阅读器供个人使用。我创建了一种从标准输入中读取整数并对其有效性进行检查的方法。这个想法是我从标准输入中读取一个字符串,进行几次检查,转换为 int,进行最后一次检查,返回已读取的值。如果同时发生任何错误,我将填写errorHint 以在std::cerr 上打印并返回std::numeric_limits<int>::min()。
我觉得这个想法实现起来非常简单直接,现在我想概括一下这个概念并制作方法模板,所以基本上我可以在编译时选择,每当我需要从标准输入中读取哪种类型的整数我想要(它可以是int、long、long long、unsigned long 等等,但是是一个整数)。为此,我创建了以下静态模板方法:
template<
class T,
class = typename std::enable_if<std::is_integral<T>::value, T>::type
>
static T getIntegerTest(std::string& strErrorHint,
T nMinimumValue = std::numeric_limits<T>::min(),
T nMaximumValue = std::numeric_limits<T>::max());
以及在同一个 .hpp 文件中的实现如下几行:
template<
class T,
class>
T InputReader::getIntegerTest(std::string& strErrorHint,
T nMinimumValue,
T nMaximumValue)
{
std::string strInputString;
std::cin >> strInputString;
// Do several checks
T nReturnValue = std::stoi(strInputString); /// <--- HERE!!!
// Do other checks on the returnValue
return nReturnValue;
}
现在的问题是,我想将刚刚读取的并且我知道在正确范围内的字符串转换为整数类型T。我怎样才能以一种好的方式做到这一点?
【问题讨论】:
-
bool success = std::cin >> T_instance;,然后(另一个)范围检查... -
为什么不直接使用
std::istringstream?
标签: c++ c++11 templates std stdstring