As wich's answer suggests, you can add an overloaded version of foo
that takes an int
argument. And since you said you wanted foo(-1)
to throw an exception, you can just have the overloaded foo()
do that:
#include <iostream>
class Wrong_Type {
public:
Wrong_Type(){}
};
void foo(unsigned n) {
std::cout << "In foo, unsigned n = " << n << "\n";
}
void foo(int n) {
std::cout << "In foo, int n = " << n << "\n";
throw Wrong_Type();
}
int main() {
try {
foo(-1);
}
catch (Wrong_Type) {
std::cout << "Caught Wrong_Type exception\n";
}
}
When I run this, the output is:
In foo, int n = -1
Caught Wrong_Type exception
But this is not an ideal solution, since it throws the exception based on the type of the argument, not its value. Both 1
and -1
are of type int
, so calling foo(1)
will also throw an exception. And some otherwise valid calls, such as foo(1.0)
, become ambiguous.
If you can replace foo(1)
by foo(1U)
, where 1U
is a constant of type unsigned int
, then this could work.