dimanche 13 mars 2022

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?

Aucun commentaire:

Enregistrer un commentaire