I'm writing a library and it should stringify objects.
I've chosen to support operator<<(ostream&...
.
Another thing is that my library should provide default stringification of types that don't have operator<<(ostream&...
in the {?}
form.
The problem is with templated types like vector<>
- I don't want the user to write 2 overloads for vector<int>
and vector<float>
- but I cannot get it to work.
Here is the code:
#include <string>
#include <type_traits>
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
namespace has_insertion_operator_impl {
typedef char no;
typedef char yes[2];
struct any_t {
template <typename T>
any_t(T const&);
};
no operator<<(ostream const&, any_t const&);
yes& test(ostream&);
no test(no);
template <typename T>
struct has_insertion_operator {
static ostream& s;
static T const& t;
static bool const value = sizeof(test(s << t)) == sizeof(yes);
};
}
template <typename T>
struct has_insertion_operator : has_insertion_operator_impl::has_insertion_operator<T> {};
template <class T>
typename enable_if<has_insertion_operator<T>::value, string>::type stringify(const T& in) {
stringstream stream;
stream << in;
return stream.str();
}
template <class T> // note the negation here compared to the one above
typename enable_if< ! has_insertion_operator<T>::value, string>::type stringify(const T&) {
return "{?}";
}
// USER CODE:
struct myType {};
ostream& operator<<(ostream& s, const myType&) { s << "myType"; return s; }
template<typename T>
ostream& operator<<(ostream& s, const vector<T>&) { s << "vector<T>"; return s; }
int main() {
myType a; cout << stringify(a) << endl; // prints "myType"
cout << stringify(6) << endl; // prints "6"
vector<int> v(5); cout << stringify(v) << endl; // prints "{?}" instead of "vector<T>"
return 0;
}
myType
and the integer both get stringified but for the vector<int>
I get the default {?}
.
I need help on this - it is a showstopper for me. I need user-provided operator<<(ostream&...
overloads to work out-of-the-box without modification - and all this in C++98.