Boost logo

Boost :

From: Preston A. Elder (prez_at_[hidden])
Date: 2005-04-16 00:45:11


Hi,

I am wondering how to create a 'type trait' such as 'is_ostreamable', ie:

class A {};
class B {};

std::ostream &operator<<(std::ostream &os, const A &in)
{ return (os << in); }
// Note, no operator<< for class B

// --- somewhere else .. ;)

class X
{
    std::ostream out;

    template<typename T>
    void Impl(const T &in, boost::mpl::bool_<true>)
    {
        out << "(" << typeid(in) << ") " << in;
    }
    template<typename T>
    void Impl(const T &in, boost::mpl::bool_<false)
    {
        out << "(" << typeid(in) << ") 0x" <<
            std::hex << (unsigned int) &in;
    }

public:
    X(std::ostream &os) : out(os) {}

    template<typename T>
    void DoIt(const T &in)
    {
        Impl(in, boost::mpl::bool_<boost::is_ostreamable<T> >());
    }
};

So the above would print the type name, and then the value of the entry IF
the entry could be streamed to a std::ostream. Otherwise, it would print
the type name and the address of its memory location (in hex).

Obviously the above is just an example, but one that illustrates my need :)
Question is, how to do it? Its easy enough to get a compiler error when
something is not supported, but how to get the compiler to choose behavior
on whether something is supported.

-- 
PreZ :)
Founder. The Neuromancy Society (http://www.neuromancy.net)

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk