My goal is to design a String class that decorates std::string in order to provide some functionality my program needs. One functionality I want to add is the ability to convert anything to my String implicitly in order to save some typing.
In order to achieve the implicitly conversion I designed the following class:
std::ostream& operator<<(std::ostream& o, const String& s);
class String {
public:
template<typename t_value>
String::String(t_value value) {
std::ostringstream oss;
oss << value;
_str = oss.str();
}
private:
std::string _str;
}
This works fine with any type that has the <<
operator defined. The problem came up with any class that doesn't have the stream operator. A compiler error would be fine but what I got is an infinity recursion since C++ tries to use my global <<
operator to try to convert to my String type.
My primary objective is to code like this
class Foo {
int _memberWithUnderscoreInName;
}
String s = Foo();
And get a compiler error instead of an infinite loop in the constructor.
Is there a simple solution for this?