简体   繁体   English

检查输入的类型是否正确

[英]Check if input is of correct type

I have a template class which can take all kinds of types: int, double etc. I want to check if the user has inputted the correct type. 我有一个模板类,它可以采用所有类型:int,double等。我想检查用户是否输入了正确的类型。 If the object was instantiated with int the user should input an int, if it was with double he should input a double and so on. 如果对象是用int实例化的,则用户应输入一个int,如果是int,则用户应输入double,依此类推。 I want to be able to do this no matter if the input comes from file or keyboard. 无论输入来自文件还是键盘,我都希望能够做到这一点。 I have 2 questions. 我有两个问题。

  1. Should I do the checking in the definition of the ">>" operator overloading? 我应该检查“ >>”运算符重载的定义吗?
  2. How do I do the checking? 我该如何检查? Do I create a template function that checks for any kind of type? 我是否创建用于检查任何类型的模板函数?

I want something like this: 我想要这样的东西:

template <class Ttype>
class foo 
{
    Ttype a,b,c; 
    friend istream &operator>> <>( istream &input, foo<Ttype> &X );
    //methods
};

template <class Ttype> istream &operator>>( istream &input, foo<Ttype> &X )
{
    //check if X.a,X.b,X.c are of Ttype
    input>>X.a>>X.b>>X.c;
}

int main()
{
    foo<int> a;
    cin>>a;

    foo<double> b;
    cin>>b;

    return 0;
}

You can't check the input before you have read it. 阅读输入之前,您无法检查输入。 The only thing I can think of is to read the input into a string (which will always work for text files or stdin) and try to convert it into your expected type. 我唯一能想到的就是将输入读取为字符串(该字符串始终适用于文本文件或stdin),然后尝试将其转换为所需的类型。 While converting you can look for exceptions. 转换时,您可以查找异常。

It seems all you want is to try to read from the istream and fail if the reading fails. 似乎您想要做的就是尝试从istream读取,如果读取失败,则失败。 In that case you can use the implicit bool-likeness of the istream after the extraction operation. 在这种情况下,可以在提取操作之后使用istream的隐式布尔型。

template <class T>
class Foo {
    T a,b,c;
    friend std::istream& operator>>(std::istream& input, Foo& X ) {
      if (!(input >> X.a >> X.b >> X.c)) { // examine the istream
        std::cerr << "extraction failed\n";
      }
      return input;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM