接受左值、右值和右值引用的 C++ 函数签名

C++ function signature that accepts lvalue, rvalue and rvalue ref

假设我有如下函数:

print_sutff(const std::string stuff) {
    std::cout << stuff;
}

我可以接受:

std::string
std::string&
std::string&&

对函数代码的外观没有任何影响。

但是可以通过多种方式调用该函数,我希望通过它实现以下行为(或尽可能接近它):

auto pass = "a string";
print_sutff(pass);

这里用户不能使用&&,我宁愿&优先使用lvaue

或:

print_sutff("a string"); 

此处应调用 && 构造函数。

所以我的问题是:

有什么方法可以让函数接受左值、& 和 && 吗?如果是这样,是否有任何方法可以根据调用它的上下文来确定使用哪个的优先级?

如果不是,有没有办法让一个函数同时接受 & 和 && ?这意味着使用哪个签名的行为是明确定义的。

只需这样做:

void print_stuff(std::string const& stuff) {
    std::cout << stuff;
}

A const 左值引用可以接受左值或右值。如果您不修改输入,这是一个很好的默认值。


,因为我们是 C++17,更喜欢:

void print_stuff(std::string_view );