I'm trying to write a method that takes a class derived from std::string as an argument. The method is overloaded with several different function signatures. I'd like compilation to fail if I try to call it with a std::string, or at the very least a runtime error but apparently the compiler is too smart for me.
class NotAString : public std::string {
NotAString(std::string str) : std::string(str) { }
};
class Foo {
Foo();
void bar(NotAString);
void bar(int)
};
This compiles and runs
Foo foo();
foo.bar(NotAString("baz"));
But so does this:
Foo foo();
foo.bar(std::string("baz"));
I've tried using typeid(str) like so:
void Foo::Bar(NotAString str) {
if(typeid(&str) != typeid(new NotAString()) {
throw std::bad_typeid();
}
}
But it always throws an exception if a pass it a std::string or NotAString. I've tried using a dynamic_cast like so:
void Foo::Bar(NotAString str) {
if (dynamic_cast<NotAString*>(&str) == NULL) {
throw std::bad_type();
}
}
But it never throws an exception.
The goal is to be able to differentiate between a string and a string that represents a key for a key-value lookup. How can I change my NotAString class or enforce some more rigorous type checking by the compiler to get this to work how I would like?