【问题标题】:No known conversion from 'A' to 'A &&' for 1st argument第一个参数没有从“A”到“A &&”的已知转换
【发布时间】:2020-08-26 00:21:04
【问题描述】:

我不熟悉 C++ 中的右值和左值。我在玩它。我不确定为什么以下代码有效:

class A {
    public:
    A() {
        std::cout<<"Constructor called"<<std::endl;
    }
    A(const A& a) {
        std::cout<<"Copy Constructor called"<<std::endl;
    }
};

template<typename T>
void printA(T&& b) {
    std::cout<<"Print method called"<<std::endl;
}

int main() {
    // your code goes here
    A a;
    printA(a);
    return 0;
}

但如果我将 printA 方法更改为以下代码,则代码无法编译:

void printA(A&amp;&amp; b)下面是完整代码:

class A {
    public:
    A() {
        std::cout<<"Constructor called"<<std::endl;
    }
    A(const A& a) {
        std::cout<<"Copy Constructor called"<<std::endl;
    }
};

void printA(A&& b) {
    std::cout<<"Print method called"<<std::endl;
}

int main() {
    // your code goes here
    A a;
    printA(a);
    return 0;
}

编译器抛出以下错误:

candidate function not viable: no known conversion from 'A' to 'A &amp;&amp;' for 1st argument

我知道我们可以通过使用std::move 将左值引用转换为右值引用来使上述代码工作,但不知道为什么我在帖子开头分享的代码工作正常!

有人可以告诉我我在这里做错了什么吗?谢谢!

【问题讨论】:

标签: c++ templates rvalue lvalue stdmove


【解决方案1】:

在这个函数模板中:

template<typename T>
void printA(T&& b) {
    std::cout<<"Print method called"<<std::endl;
}

T&amp;&amp; 是一个forwarding reference。这意味着它可以绑定到左值或右值:

A a;
printA(a); // ok, l-value
printA(A{}); // ok, r-value

不过,这是一个常规函数,它采用 恰好 一个右值:

void printA(A&& b) {
    std::cout<<"Print method called"<<std::endl;
}

所以只能用右值调用:

A a;
printA(a); // error, can't bind r-value to l-value
printA(A{}); // ok, r-value

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 2022-12-04
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2020-06-08
    相关资源
    最近更新 更多