0

I'm very new to c++ and I can't believe I can't find a simple answer whether it is possible to call a function having a template as argument, without having to initialize that template first.

I'd like to be able to call my function directly such as:

#include <map>
#include <string>

void foo(std::multimap<std::string, int> &bar)
{
    ...
}

int main(int ac, const char *av[])
{
    foo({{"hello", 1}, {"bye", 2}});
    return (0);
}

Is there a way to do this in c++?

fassn
  • 299
  • 1
  • 5
  • 15
  • 4
    Just change the method signature to `void foo(const std::multimap& bar)` and it will work. The issue in your current code is that your method signature expects an lvalue. You are calling it with an rvalue. If you change the method signature, the const& can bind to an rvalue as well. So the code will work. – cplusplusrat Feb 14 '19 at 02:04
  • 1
    What's the point of having the function take a reference if you're storing the original variable anywhere anyway? – Rietty Feb 14 '19 at 02:04
  • @Rietty: Lack of copies – Mooing Duck Feb 14 '19 at 02:18
  • @MooingDuck huh. I see. move semantics are a bit odd. – Rietty Feb 14 '19 at 02:20
  • @Rietty: Oh, you're right that _this particular_ case wouldn't have copied, and would have moved. But all it takes is for someone to pass in a local map, and suddenly there's a copy. `const&` never copies (though can still convert, which can be bad) – Mooing Duck Feb 14 '19 at 02:21

1 Answers1

3

A non-const reference to a temporary variable isn't allowed because the temporary would go out of scope before you got a chance to do anything with it and leave you with a dangling reference.

You can

void foo(std::multimap<std::string, int> bar)
{
    ...
}

or, since const references get a free lifetime extension,

void foo(const std::multimap<std::string, int> &bar)
{
    ...
}

if you don't want the function to modify the multimap.

Useful extra reading:

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

Why do const references extend the lifetime of rvalues?

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • omg, I was poking around for 2h... This is so simple. So close yet so far :D Thank you ! – fassn Feb 14 '19 at 02:15