开发者

Why does ref in C++0x not behave as expected?

I'm very sorry for my previous miswording. So I rephrased this question as follows:

The simplest C++0x code below should be not valid:

#include <functional>

template<class T_>
void f(T_ obj) 
{
    Obj++; // OK that is as expected.
    static_cast<int&>(obj) = 开发者_如何学C2; // Though ugly, this is still OK.

    obj = 2; // However, this line will generate a compiler error
}

int main()
{
    int i = 1;
    f(std::tr1::ref(i));
}

Who can tell me the exact semantics of ref?


The cause of the error is that there is no suitable assignment operator to apply. The only candidate is this:

reference_wrapper& operator=(const reference_wrapper<T>& x);

A reference_wrapper acts as a reference with the help of implicit conversion operators:

operator T& () const;

However, an implicit conversion will not happen on the left side of the assignment operator.

If you are expecting this template to support reference_wrapper, perhaps you can work around in ways like this:

#include <functional>
#include <iostream>

template <class T>
T& get(T& value)
{
    return value;
}

template <class T>
T& get(std::reference_wrapper<T>& w)
{
    return w.get();
}


template<class T_>
void f(T_ obj)
{
    //obj = 2;
    get(obj) = 2;
}

int main()
{
    int i = 1;
    f(std::ref(i));
    std::cout << i << '\n';
    f(3.14); //at the same time, we want this also to work
}

As to why reference_wrapper doesn't have an assignment operator for stored type, not sure. Boost's version doesn't have either, and they simply say that this class "usually allows the function templates to work on references unmodified". Guess this is just not one of those cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜