I just found out how to check if operator<<
is provided for a type.
template<class T> T& lvalue_of_type();
template<class T> T rvalue_of_type();
template<class T>
struct is_printable
{
template<class U> static char test(char(*)[sizeof(
lvalue_of_type<std::ostream>() << rvalue_of_type<U>()
)]);
template<class U> static long test(...);
enum { value = 1 == sizeof test<T>(0) };
typedef boost::integral_constant<bool, value> type;
};
Is this trick well-known, or have I just won the metaprogramming Nobel prize? ;)
EDIT: I made the code simpler to understand and easier to adapt with two global function template declarations lvalue_of_type
and rvalue_of_type
.
is_printable<X>::value
is true for any X, and with Comeau Online it appears to be false for any X. – Earthlightis_printable<int>::value
and 0 foris_printable<std::vector<int> >::value
, so it works fine for me. – Graybilltemplate <typename X, typename Y> static auto check(X& x, Y& y) -> decltype(x << y);
– Trappist