首页 > 解决方案 > 使用模板函数进行通用输入验证

问题描述

我想创建一个循环直到用户输入正确的输入类型的函数。我是使用模板的新手,但我想如果我想验证通用类型,那么模板函数将是正确的工具。我希望该函数一直要求用户输入输入,直到类型与模型类型匹配。

所以这是我到目前为止的尝试(抛出错误:'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;”在线发生?

标签: c++validationc++11templates

解决方案


引发错误:“输入”:未声明的标识符

这是因为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:");

不要依赖从(否则未使用的)参数的类型推导,只需让用户直接传递类型。


推荐阅读