使用模板功能进行通用输入验证

时间:2019-05-08 11:00:47

标签: c++ validation c++11 templates

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

这是我到目前为止的尝试(这会引发错误:'input':未声明的标识符)

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:");

使用未使用的模型参数会强制输入变量为同一类型吗? (这也是使用未使用的参数的不良编程习惯吗?)

是否有一种更优雅的方式来编写常规的验证检查循环?

编辑:为什么未声明的标识符错误出现在“返回输入;”行上?

2 个答案:

答案 0 :(得分:0)

  

这将引发错误:'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:");

让用户直接传递类型,而不是依靠(否则未使用的)参数的类型推导。

答案 1 :(得分:0)

您在input循环范围之外返回for,而在内部将其声明。

只需将声明移出循环。

#include <iostream>
using namespace std;

template <typename T>
T check_input(T model_input, string message)
{
    T input; // will it make the input type the same type as model input used in the arg?
    for (;;)
    {
        cout << message << endl;
        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; 
}

int main () 
{
    string model_type = "exp";
    string exp_name = check_input(model_type, "Please enter the experiment name:");
}

观看现场演示here