[英]C++: Pass string literal or variable to function
我有一个 function f
,它接受一个字符串作为输入。 我通常想提供一个字符串文字,例如f("hello")
。 但是,我想实现另一个基于f
的 function g
:
std::string f(const std::string&& x) {
return x + " world";
}
std::string g(const std::string&& x) {
std::string res = f(x); // problem: rvalue reference to std::string cannot bind to lvalue of type std::string
res += "!";
return res;
}
int main() {
std::string res_a = f("hello");
std::string res_b = g("world");
return 0;
}
我如何在 C++11/14 中以一种可以将f
与字符串文字和变量一起使用的方式实现这一点?
解决 function 同时采用左值和右值引用的问题的通用方法是使用模板化函数,例如 -
template <typename T>
T f(T&& val) {
}
template <typename T>
T g(T&& val) {
T some_val = f(std::forward<T>(val));
}
std::foward<T>(val)
将左值作为左值转发,将右值作为右值转发,正如其名称所暗示的那样。
通过模板化 function,您可以确保此逻辑适用于任何类型,而不仅仅是字符串。
获取只读参数的传统方法是通过const
左值引用。
std::string f(const std::string& x)
这个经验法则适用于许多类型,而不仅仅是std::string
。 主要的例外是不大于指针的类型(例如char
)。
function 有一个const
右值引用是相当不寻常的。 正如您所发现的,这会在尝试将变量作为参数传递时增加难度。 非const
右值引用具有值,但在大多数情况下, const
右值引用不如const
lvaue 引用。 另请参见对 const 的右值引用是否有用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.