WhatABeautifulWorld
WhatABeautifulWorld

Reputation: 3388

template function with default value

I have a template function:

template <typename T>
void foo(const T& container = {}) {
  // ... some implementation
}

Now I can call

foo<std::vector>(some_vector_param) or foo<std::map>(some_map_param)

As I have default value for the container, I should be able to call without any param.

foo()

But at this point, the compiler doesn't know how to translate it as it could be a vector or a map. One solution is to explicitly specify the type.

foo<vector>()

Is there a way for me to avoid that? Can I let the compiler use vector if the input type is missing?

Upvotes: 3

Views: 53

Answers (1)

Oliv
Oliv

Reputation: 18051

Template parameters can have default argument too:

template <typename T = vector<int>>
void foo(const T& container = {}) {
  // ... some implementation
  }

Upvotes: 4

Related Questions