引用 const 对象但没有右值的函数

Function that takes a reference of a const object but no r-value

目前是否可以编写引用 const 合格对象但没有右值的函数?

// Takes no r-values
void foo(std::string& v) {
    ...
}
...
const string cstr("constant string");
foo("string"); // this does not compile, as wanted
foo(cstr); // this does not compile, as expected. But i would want it to 
...

// Takes r-values, which is highly undesired
void foo2(const std::string& v) {
    ...
}
...
const string cstr("constant string");
foo("string"); // this does compile, but i want it to fail.
foo(cstr); // this does compile
...

问题的背景与稍后时间点(foo 完成后)的对象副本有关。基本上,引用被推送到队列并稍后处理。我知道,语义被搞砸了,需要 shared_ptr 或类似的东西。但我受制于外部约束。

感谢您的建议。

使用已删除的函数重载:

void foo(std::string& v) {
    std::cout << v;
}
void foo(const std::string& v) = delete;
void foo(const char* v) = delete;

或类似。

您可以明确允许 const 引用,同时禁止 r 值引用:

void foo(const std::string& v) {
}

void foo(std::string& v) {
}

void foo(std::string&& v) = delete;