c++ - 在不再次使用 std::move(t) 的情况下重复调用 f(T&& t) 形式的函数?

标签 c++

#include <iostream>
#include <cstdlib>
#include "A.h"

void second(const A& a)
{
    std::cout << "void second(const A& a)." << std::endl;
}

void second(A&& a)
{
    std::cout << "void second(A&& a)." << std::endl;
}

void first(const A& a)
{
    std::cout << "void first(const A& a)." << std::endl;
    second(a);
}

void first(A&& a)
{
    std::cout << "void first(A&& a)." << std::endl;
    second(a); //Make this call void second(A&& a) without using std::move(a) again?
}

int main()
{
    std::cout << "int main()." << std::endl;

    A a;
    first(std::move(a));

    std::cin.sync();
    std::cin.get();
    return EXIT_SUCCESS;
}

最佳答案

second(a);

它不能调用 second(A&&) 因为 a 是一个左值(因为它有一个名称)。

要调用 second(A&&),您需要一个右值。因此,您需要将 a 转换为右值,为此您必须使用 move 或进行手动显式转换:

second(std::move(a));        //invokes second(A&&)
second(static_cast<A&&>(a)); //invokes second(A&&)

希望对您有所帮助。

关于c++ - 在不再次使用 std::move(t) 的情况下重复调用 f(T&& t) 形式的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14307688/

相关文章:

c++ - 数据类型限制

c++ - "' omp.h ' file not found"使用 Clang 编译时

c++ - template specialization中的type会继续计算吗?

c++ - 如何在不使用 GL_LINE_SMOOTH 的情况下使用 OpenGL 在 2D 场景中绘制平滑线条?

C++ 多态类、虚函数和性能转换

c++ - 对象上的范围解析运算符

C++ OpenMP 写入共享数组/vector 的特定元素

c++ - 这个 ISR 程序是如何工作的?

c++ - 有没有办法在 VS 调试器中自定义自定义对象的工具提示?

c++ - 对函数的引用不明确