It's apparently this overload of operator<<
that's stepping in your way and making the expression in traling return type valid:
template< class CharT, class Traits, class T >
basic_ostream< CharT, Traits >& operator<<( basic_ostream<CharT,Traits>&& os,
const T& value );
See (3) on this reference page. It's a simple forwarder (calling os << value
) that was added in C++11 to allow insertion to rvalue-streams because they don't bind to overloads taking an lvalue reference.
So, the problem is that std::declval<SS>()
returns an rvalue reference and this overload kicks in. The call itself is well-formed, but because the function itself does not get instantiated you don't get an error even if value is not streamable.
This can be sidestepped if you explicitly ask for lvalue reference: std::declval<SS&>()
.
I'd also suggest a slightly different implementation, without passing stream and value to test
. You can use declval
directly inside decltype
. Together with comma operator, it looks like this:
#include <type_traits>
#include <utility>
#include <iostream>
#include <sstream>
template<typename S, typename T>
class is_streamable
{
template<typename SS, typename TT>
static auto test(int)
-> decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() );
template<typename, typename>
static auto test(...) -> std::false_type;
public:
static const bool value = decltype(test<S,T>(0))::value;
};
class C {};
int main() {
std::cout << is_streamable<std::stringstream, C>::value << std::endl;
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…