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 con
Instead of declaring the output operator in the surrounding namespace, only declare it as a friend of the String
class:
class String {
public:
// This must be implemented inline here
friend std::ostream& operator<<(std::ostream& o, const String& s) {
return o << _str; // for example
}
template
String(t_value value) {
std::ostringstream oss;
oss << value;
_str = oss.str();
}
private:
std::string _str;
};
Now it can only be found by argument-dependent lookup, and so will only be considered if the second argument really is of type String
, not just convertible to it. Therefore, it won't be considered as a candidate for os << value
in the constructor, giving a compile error rather than a run-time death spiral if there is no other candidate.