是否可以调用一个以 const 右值作为参数的函数?

Is it possible to call a function which takes a const rvalue as a parameter?

最近我不小心编写了以下程序:

void someFunction(const SomeClass&& value){
    //Some Code
}

我不是有意在 value 参数中添加 'const' 关键字的。然而,这让我想到:是否有可能以某种方式调用此函数,如果存在不带 const 的等效函数?如果是,这是否有意义,是否有实际用途?

此代码:

#include <iostream>
using namespace std;

struct s{};     

void someFunction(s& value){ std::cout << "ref" << std::endl; }

void someFunction(const s&& value){ std::cout << "const" << std::endl; }

void someFunction(s&& value){ std::cout << "non const" << std::endl; }

const s foo() { return s(); }
s bar() { return s(); }


int main() {
    someFunction(bar());
    someFunction(foo());
    return 0;
}

Prints

non const
const

一些解释(我无法提供;)请参考 this site。最相关的引用是:

[...] This makes const rvalue references pretty useless. Think about it: if all we need is a non-modifiable reference to an object (rvalue or lvalue), then a const lvalue reference does the job perfectly. The only situation where we want to single out rvalues is if we want to move them. And in that case we need a modifiable reference.

我能想到的唯一用例是使用 someFunction 来检测第二个函数 returns 是 const 还是非 const,但我猜有更简单的方法可以找出答案。

作为旁注:当您在上面的代码中将 s 替换为 intit prints:

non const 
non const

那是因为(引自同一网站,来自 pizer 的评论):

There are no const prvalues of scalar types. For a const rvalue you either need an Xvalue and/or a class-type object. [...]