Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: Pass string literal or variable to function

I have a function f that takes a string as input. I usually want to provide a string literal, e.g., f("hello"). However, I want to implement another function g that builds upon f:

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;
}

How can I achieve this in C++11/14 in a way that I can use f with string literals as well as variables?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A generic way of solving the problem of a function taking both l-value and r-value references is to use templated functions like so-

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) forwards an l-value as an l-value and an r-value as an r-value, just as its name implies.

By templating the function, you ensure that this logic works for any type and not just strings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading