vendredi 30 mars 2018

How to pass an rvalue as a reference argument to a function

I have a function that takes the reference of an object. In one particular call instance, I don't care how the function process that particular object. Hence I wish I could avoid creating that object in the main function.

The code looks like:

#include <stdio.h>
#include <unordered_map>

void myFunc(std::unordered_map<int,int> &mp);

int main() {
  myFunc(std::unordered_map<int,int>());
  return 0;
}

void myFunc(std::unordered_map<int,int> &mp) {
  printf("%d\n",mp.size());
  printf("Hello world.\n");
}

The bottom line is: I don't want to declare and initialize an unordered_map<int,int> object in the main function. This version of the code reports:

error: invalid initialization of non-const reference of type ‘std::unordered_map&’ from an rvalue of type ‘std::unordered_map’

I also tried const_cast<> and std::move, but neither works.

The error can be removed if we change the API to:

void myFunc(std::unordered_map<int,int> &&mp)

The problem is that the API is shared among multiple files, and we really don't want to change it. Given the API of myFunc has to be fixed, how can I modify main() such that I don't need to explicitly create an object?

Aucun commentaire:

Enregistrer un commentaire