简体   繁体   English

接受左值,右值和右值ref的C ++函数签名

[英]C++ function signature that accepts lvalue, rvalue and rvalue ref

Assuming I have a function like the following: 假设我有如下功能:

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

I can accept: 我可以接受:

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

Without any influence on how the function code looks like. 对功能代码的外观没有任何影响。

However the function could be called in multiple ways, with which I'd like to achieve the following behavior (or as close to it as possible): 但是,可以通过多种方式调用该函数,以实现以下行为(或尽可能接近):

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

Here the user can't use the &&, I would prefer to & to take priority to lvaue 在这里,用户不能使用&&,我宁愿&优先使用lvaue

or: 要么:

print_sutff("a string"); 

Here the && constructor should be invoked. 在这里,&&构造函数应该被调用。

So my question is: 所以我的问题是:

Is there any way to make a function accept lvalue, & and && ? 有什么方法可以使函数接受左值&和&&? And if so, is there any way to prioritize which one is used based on the context where it is called ? 如果是这样,是否有任何方法可以根据调用上下文确定使用哪个优先级?

If not, is there any way to make a function accept both & and && ? 如果不是,是否有任何方法可以使函数同时接受&和&&? Which would mean the behavior of which signature is used which is well defined. 这将意味着使用哪个签名的行为已得到很好的定义。

Just do this: 只要这样做:

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

A const lvalue reference can accept either lvalues or rvalues. const左值引用可以接受左值或右值。 If you're not modifying the input, that's a good default. 如果您不修改输入,那是一个很好的默认设置。


Even better , since we're C++17, prefer: 甚至更好 ,因为我们是C ++ 17,所以更喜欢:

void print_stuff(std::string_view );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM