Reputation: 155
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.
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
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
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