M
Markus Dehmann
I think this is a question about automatic type conversion, but I
didn't find the answer after googling for these words ...
I have a class called Value (source see below) which can hold an int
or a string:
Value i(23);
Value s("blah");
Now I want an implicit conversion that automatically returns the
correct type, even in a context like this:
std::cout << i; // works
std::cout << s; // doesn't work: "Not an int" exception thrown
I think this should be feasible because the object knows what to
return (it was constructed with the certain type, although that's only
at runtime, not compile time ...). Of course, I could have an
asString(), or an asInt() method in the class, but I want to avoid
that as it seems redundant. I also don't want to use external (non-
std) packages like boost.
Thanks for any help! The class I have so far is this:
class Value {
std::string stringValue;
int intValue;
bool isString;
bool isInt;
public:
Value(std::string s) : isString(true), isInt(false),
stringValue(s) {}
Value(int i) : isString(false), isInt(true), intValue(i) {}
operator std::string (){
if(!isString){throw std::runtime_error("Not a string");}
return stringValue;
}
operator int (){
if(!isInt){throw std::runtime_error("Not an int");}
return intValue;
}
};
didn't find the answer after googling for these words ...
I have a class called Value (source see below) which can hold an int
or a string:
Value i(23);
Value s("blah");
Now I want an implicit conversion that automatically returns the
correct type, even in a context like this:
std::cout << i; // works
std::cout << s; // doesn't work: "Not an int" exception thrown
I think this should be feasible because the object knows what to
return (it was constructed with the certain type, although that's only
at runtime, not compile time ...). Of course, I could have an
asString(), or an asInt() method in the class, but I want to avoid
that as it seems redundant. I also don't want to use external (non-
std) packages like boost.
Thanks for any help! The class I have so far is this:
class Value {
std::string stringValue;
int intValue;
bool isString;
bool isInt;
public:
Value(std::string s) : isString(true), isInt(false),
stringValue(s) {}
Value(int i) : isString(false), isInt(true), intValue(i) {}
operator std::string (){
if(!isString){throw std::runtime_error("Not a string");}
return stringValue;
}
operator int (){
if(!isInt){throw std::runtime_error("Not an int");}
return intValue;
}
};