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

Out*_*und 1 c++ function pass-by-reference

目前是否可以编写函数,它接受const合格对象的引用,但没有r值?

// 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 
...
Run Code Online (Sandbox Code Playgroud)
// 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
...
Run Code Online (Sandbox Code Playgroud)

问题的背景与稍后的对象副本有关(在foo完成之后).基本上,引用被推送到队列并稍后处理.我知道,语义混乱,需要一个shared_ptr或类似的东西.但我与外部约束有关.

谢谢你的建议.

Ron*_*Ron 6

使用已删除的函数重载:

void foo(std::string& v) {
    std::cout << v;
}
void foo(const std::string& v) = delete;
void foo(const char* v) = delete;
Run Code Online (Sandbox Code Playgroud)

或类似的.