Boost logo

Boost :

Subject: [boost] [TypeErasure] references
From: Chapman, Alec (archapm_at_[hidden])
Date: 2012-07-26 13:31:43


Hi Steven,

I have a somewhat-generic type erasure class that I would like to switch to yours. The main difficulty I can see is in the way capturing by reference is handled. The approach I take in my class is to pass a boost::reference_wrapper to the constructor:

typedef mpl::vector<copy_constructible<>, type_id_<>, incrementable<> > requirements;
int i = 0;
any<requirements> x(boost::ref(i)); // capture i by reference
++x; // i == 1
any<requirements> y(x); // makes a copy of i
++y; // i == 1, any_cast<int>(y) == 2

My motivation is that I have a bunch of template functions already written that I often call directly, but in other cases I need to compile them separately by instantiating them with any<...>:

---------------------- module 1 -------------------------
// some long algorithm that I don't want to modify to be aware of any<...>
template<class T>
void f(T& t)
{
    ++t;
    T t2 = t;
    ++t2; // do something with t2
}

// make a type-erased version for separate compilation
void any_f(any<requirements>& x)
{
    return f(x);
}

-------------------- module 2 ----------------------------
// provide a thin wrapper that applies type erasure before calling any_f
template<class T>
void f_fwd(T& t)
{
    any<requirements> x(boost::ref(t));
    any_f(x);
}

// some function that needs to call f
void g(int& i)
{
    // do something with i...
    // then pass it to f
    f_fwd(i);
}

Is something like this possible with your method? Are there advantages that I'm not seeing to having the type signature contain information about whether the object is held by reference?

Thanks,
Alec


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