#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/