Andy
Andy

Reputation: 155

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. 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. 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;
}

Upvotes: 0

Views: 1128

Answers (2)

Ryan Haining
Ryan Haining

Reputation: 36782

It seems all you want is to try to read from the istream and fail if the reading fails. In that case you can use the implicit bool-likeness of the istream after the extraction operation.

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;
    }
}

Upvotes: 1

Robert S.
Robert S.

Reputation: 2042

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. While converting you can look for exceptions.

Upvotes: 1

Related Questions