为什么ref在C ++ 0x不行为预期? [英] Why does ref in C++0x not behave as expected?

查看:147
本文介绍了为什么ref在C ++ 0x不行为预期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉我以前的错字。所以我改写这个问题如下:

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

下面最简单的C ++ 0x代码应该无效:

#include <functional>

template<class T_>
void f(T_ obj) 
{
    Obj++; // OK that is as expected.
    static_cast<int&>(obj) = 2; // 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));
}

谁能告诉我ref的确切语义?

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 隐式转换运算符的帮助:

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.

如果你期望这个模板支持 reference_wrapper ,也许你可以这样处理:

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
}

reference_wrapper 没有存储类型的赋值运算符,不确定。 Boost的版本没有,他们只是说,这个类通常允许函数模板工作在引用未修改。猜猜这只不是这些情况之一。

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.

这篇关于为什么ref在C ++ 0x不行为预期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆