Boost logo

Boost :

From: Preston A. Elder (prez_at_[hidden])
Date: 2005-04-16 01:25:12


On Sat, 16 Apr 2005 01:45:11 -0400, Preston A. Elder wrote:

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

Just as an FYI, here is my current attempts to get it working. With the
code as follows, both A and B show up as 'not convertable' (aka. not
streamable). As mentioned in the comments, if I uncomment the templated
constructor of streamable_object, both show up as 'convertable'.

Here is the code:

#include <cstdio>
#include <sstream>
#include <boost/type_traits.hpp>

class A
{
    int val;
public:
    A(int v) : val(v) {}
    int get() const { return val; }
};

std::ostream &operator<<(std::ostream &out, const A &in)
{
    return (out << in.get());
}

class B
{
    int val;
public:
    B(int v) : val(v) {}
    int get() const { return val; }
};

// ----------------------------------------------

template<typename T>
struct streamable_object
{
    streamable_object() {}

    // If this is uncommented, is_convertable will return true no matter
    // what class T is. But is_convertable states it doesn't work with
    // constructor-based conversions anyway, so not surprising.
    //streamable_object(const T &in)
    //{
    // std::stringstream os;
    // os << in;
    //}

    streamable_object &operator=(const T &in)
    {
        std::stringstream os;
        os << in;
    }
};

int main()
{
    printf("RES(A) = %d\n", boost::is_convertible<A, streamable_object<A> >::value);
    printf("RES(B) = %d\n", boost::is_convertible<B, streamable_object<B> >::value);

    A a(5);
    B b(10);

    std::stringstream ss;
    ss << a;
    // ERROR:
    //ss << " " << b;
    printf("RES(SS) = %s\n", ss.str().c_str());

    streamable_object<A> sa;
    sa = a;

    // ERROR:
    //streamable_object<B> sb(b);
    //sb = b;

    return 0;
}

-- 
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