[英]On the conversion from std::string type to template T type in C++
I've found on this forum the following snippet witten by user Ben Voigt:我在这个论坛上发现了以下由用户 Ben Voigt 编写的片段:
//forward declaration
template<typename T>
T getline_as(std::istream& s);
template<>
std::string getline_as<std::string>(std::istream& s)
{
std::string str;
std::getline(s,str);
return str;
}
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert(getline_as<std::string>(s));
T value;
convert >> value;
return value;
}
I am looking for a way to handle possible failures of convert >> value;
我正在寻找一种方法来处理
convert >> value;
. . My goal would be to iterate the request to the user to make it insert a given input correctly:
我的目标是迭代对用户的请求,使其正确插入给定的输入:
int main()
{
std::cout << "Please enter a number: ";
double number{getline_as<double>(std::cin)};
}
My idea was to create a do-while
loop inside getline_as
but I can't make it work.我的想法是在
getline_as
中创建一个do-while
循环,但我无法让它工作。
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert;
T value;
do
{
convert(getline_as<std::string>(s));
}
while(!(convert >> value));
return value;
}
std::stringstream convert(...);
is a constructor call, but trying to do convert(...);
是一个构造函数调用,但试图做
convert(...);
after the stream is created is illegal (it would require the stream to overload operator()
, which it doesn't do).在创建 stream 之后是非法的(它需要 stream 重载
operator()
,但它不会这样做)。 convert = std::stringstream(...)
would work, but I'd just completely recreate the stream. convert = std::stringstream(...)
会起作用,但我只是完全重新创建 stream。
You also should use a read-only std::istringstream
, since you never write anything to it.您还应该使用只读的
std::istringstream
,因为您永远不会向它写入任何内容。
I also made some cosmetic changes and ended up with following:我还进行了一些外观上的更改,最终得到以下结果:
template <typename T>
[[nodiscard]] T getline_as(std::istream &s);
template <>
[[nodiscard]] std::string getline_as<std::string>(std::istream &s)
{
std::string str;
std::getline(s, str);
return str;
}
template <typename T>
[[nodiscard]] T getline_as(std::istream &s)
{
while (true)
{
T value{};
std::istringstream convert(getline_as<std::string>(s));
if (convert >> value)
return value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.