c++ - 使用模板函数进行通用输入验证
问题描述
我想创建一个循环直到用户输入正确的输入类型的函数。我是使用模板的新手,但我想如果我想验证通用类型,那么模板函数将是正确的工具。我希望该函数一直要求用户输入输入,直到类型与模型类型匹配。
所以这是我到目前为止的尝试(抛出错误:'input': undeclared identifier)
using namespace std;
template <typename T>
T check_input(T model_input, string message)
{
for (;;)
{
cout << message << endl;
T input; // will it make the input type the same type as model input used in the arg?
cin >> input;
// if valid input then for loop breaks
if (cin.fail())
{
// prompts that there was an error with the input and then loops again
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input, please try again" << endl;
}
else
{
break;
}
}
return input;
}
用法:
string model_type = "exp";
string exp_name = check_input(model_type, "Please enter the experiment name:");
使用未使用的模型参数会强制输入变量为同一类型吗?(这也是一种糟糕的编程习惯,有一个未使用的参数吗?)
有没有更优雅的方式来编写一个通用的验证检查循环?
编辑:为什么未声明的标识符错误与“return input;”在线发生?
解决方案
引发错误:“输入”:未声明的标识符
这是因为input
在循环内部定义,但您的代码尝试在外部 ( return input;
) 使用它。
可能的修复:
for (;;)
{
cout << message << endl;
T input;
if (cin >> input) {
return input;
}
// handle input errors
...
}
使用未使用的模型参数会强制输入变量为同一类型吗?
是的。只有一个T
模板参数,因此每个实例化的check_input
第一个参数和返回值都将使用相同的类型。
模板类型推导将使用第一个参数的类型来确定T
。
(这也是一种糟糕的编程习惯,有一个未使用的参数吗?)
是的。您可以将其忽略并调用该函数
auto exp_name = check_input<string>("Please enter the experiment name:");
不要依赖从(否则未使用的)参数的类型推导,只需让用户直接传递类型。
推荐阅读
- ios - iOS 应用程序以 8 为目标,带有意图扩展程序在模拟器中崩溃
- java - 非干扰运算符不显示其内容
- c# - 在安装程序项目中更改默认图标和快捷方式名称
- java - 如何修复文档:GML 响应上的空错误
- java - Java程序无法在linux中的挂载系统上写入
- python - 如何加快这种阵列间过程?[Python,Numpy]
- c# - 如何在 asp.net core log4net 中生成基于小时的日志文件?
- excel - Excel公式对日期之间的值求和
- xamarin - Xamarin 使用命令更新视图模型
- android - 如何在颤动中删除TextField底部的空格?