fassn
fassn

Reputation: 359

How to call a function using a template as argument

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++?

Upvotes: 0

Views: 58

Answers (1)

user4581301
user4581301

Reputation: 33982

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?

Upvotes: 3

Related Questions