C++11 为什么ref在C++;0x的行为不符合预期?

C++11 为什么ref在C++;0x的行为不符合预期?,c++11,C++11,我为我以前的错误措辞感到非常抱歉。因此,我将这个问题重新表述如下: 下面最简单的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 =

我为我以前的错误措辞感到非常抱歉。因此,我将这个问题重新表述如下:

下面最简单的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));
}
#包括
模板
无效f(T_uj)
{
Obj++;//正常,这与预期的一样。
静态_cast(obj)=2;//虽然很难看,但仍然可以。
obj=2;//但是,此行将生成编译器错误
}
int main()
{
int i=1;
f(std::tr1::ref(i));
}

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

错误的原因是没有合适的赋值运算符可应用。唯一的候选人是:

reference_wrapper& operator=(const reference_wrapper<T>& x);
但是,隐式转换不会发生在赋值运算符的左侧

如果您希望此模板支持
reference\u wrapper
,也许您可以通过以下方式解决此问题:

#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
}
#包括
#包括
模板
T&get(T&value)
{
返回值;
}
模板
T&get(标准::参考_包装&w)
{
返回w.get();
}
模板
无效f(T_uj)
{
//obj=2;
get(obj)=2;
}
int main()
{
int i=1;
f(标准::参考(i));

std::cout什么是
ref
?请发布一个完整的可编译程序。-1不完整的代码,未定义的术语,对未定义的东西的主观信念的断言我喜欢这样一个。也许这将是一个新趋势的开始。发布构造做它应该做的事情的示例,然后抱怨它不能做任何事情。谁是heck在问题被实际修复后关闭了它?例如:
struct X{int&X;};intz=10;xa={z};xb={z};b=a;
不起作用,但是
struct X{tr1::reference_包装器X;};intz=10;xa={tr1::ref(z)};xb={tr1::ref(z)};b=a;
确实如此。您的解决方案是可行的。但这似乎不是处理真实引用和引用包装的最统一的方法。在我看来,get(obj)=2;远不如obj=2优雅;@UncleBens:“至于为什么reference_wrapper没有存储类型的赋值运算符,还不确定。Boost的版本也没有,他们只是说这个类“通常允许函数模板在未修改的引用上工作”。我猜这不是其中之一。“@UncleBens:你的解释很有说服力。我认为这是为了防止隐式修改引用的对象。否则,通过添加一个membe函数,比如T&operator=(const T&obj){return m_realObj=obj;}就很容易做到这一点。故意不提供这样的成员函数可以防止程序员误用。@xmlmx reference\u wrapper是用于传递引用的包装器,如果允许赋值运算符,则会破坏其语义。在这种情况下,编译器会怎么做
int x;int&y=x;reference\u wrapper z=y;int a=10;int&b=a;z=b;
?它是将10存储到x中还是仅仅更改包装器引用?
#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
}