Boost logo

Boost :

Subject: [boost] [conversion] How to repere assignement to a variable? (was [property] interest in C# like properties for C++?)
From: vicente.botet (vicente.botet_at_[hidden])
Date: 2009-10-22 10:44:45

in the thread about C# like properties we were talking about the advantage to be able to repere assignation to properties. I said that, another way to repare the assignments is to use a free function assign_to, like we use the free function swap, or the cast family functions.

    assign_to(a.p_X, 1);

assign_to call by default the assignment operator.

If we want transitive assignation

    a = b = c;

we could do

    assign_to(a, assign_to(b, c));

and if we find this not really readable we can try with

    tie(a) = tie(b) = c;

tie is a template function returning an ca_wrapper.

    template <typename T>
    ca_wrapper <T> tie(T& r) {
        return ca_wrapper<T>(r);

ca_wrapper is responsable to transforming the assignation and operator conversion on a call to assign_to and no more.

    template <typename T>
    class ca_wrapper {
        T& ref_;
        ca_wrapper(T& r) : ref_(r) {}
        template <typename U>
        T& operator =(U const& u) {
            return assign_to(ref_, u);
        template <typename U>
        operator U() {
            return convert_to(ref_, u);

The advantage of having a specific function is that we can specialize the assign_to function for unrelated classes.
The Boost.Conversion library (on the review schedule) defines two free functions convert_to and assign_to which by default use the conversion operator and the assignment. We can see convert_to as a getter and assign_to as a setter.

The major advantage is that with a uniform syntax, the user can however specialize them to do conversion and assignations between unrelated types.

I don't know if tie is a good name to manage with assignation of a variable, I have taken the name from the Boost.Tuple?

Vicente Juan Botet Escribá

P.S. tie and ca_wrapper are new features of Boost.Conversion v.0.3

Boost list run by bdawes at, gregod at, cpdaniel at, john at