8

为什么这个右值调用模棱两可?我可以拥有 AA 和 AA& 并且编译器会知道使用AA&. 但是当我添加第三个选项时,我得到了一个错误。显然 AA&& 是一个更好的重载,然后其他像 int 的 int 比 long 更好。为什么这是模棱两可的?有没有办法可以保留所有 3 个重载并明确我想要哪个?(类型转换(AA&&)不会这样做)。

struct AA{
    void*this_;
    AA() { this_=this; }
    //not valid, use AA&, AA(AA a){ this_=this; }
    AA(AA&a){ this_=this; }
    AA(AA&&a){ this_=a.this_; }
};
void movetest(AA s) {}
void movetest(AA& s) {}
//This gets me the ambiguous error void movetest(AA&& s) {}
AA&& movetest() { return AA(); }
void MyTestCode2(){
    AA a;
    AA b(a);
    AA c = movetest();
    movetest(AA());
}
4

2 回答 2

8

我可以有 AA 和 AA& 并且编译器会知道使用 AA&

是的,在movetest(AA()) 的情况下;,只有movetest(AA)是可行的,因为对非常量的(左值)引用不能绑定到右值。但是,右值引用被称为直接绑定到临时对象。因此,为了重载决议的目的,函数

void movetest(AA)
void movetest(AA&&)

是相等的,因为分别用于将AA()转换为AAAA&&的隐式转换序列是相等的。前者并不好,因为直接引用绑定也被认为是一种身份转换。

于 2011-04-08T06:41:36.843 回答
2

同意decltype。这实际上与 C++03/98 的歧义没有什么不同:

struct AA {};

void movetest(AA s) {}
void movetest(AA& s) {}

int main()
{
    AA a;
    movetest(a);
}

test.cpp:9:5: error: call to 'movetest' is ambiguous
    movetest(a);
    ^~~~~~~~
test.cpp:3:6: note: candidate function
void movetest(AA s) {}
     ^
test.cpp:4:6: note: candidate function
void movetest(AA& s) {}
     ^
1 error generated.
于 2011-04-08T15:30:36.800 回答