Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template function with default value

Tags:

c++

templates

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?

like image 636
WhatABeautifulWorld Avatar asked May 28 '26 19:05

WhatABeautifulWorld


1 Answers

Template parameters can have default argument too:

template <typename T = vector<int>>
void foo(const T& container = {}) {
  // ... some implementation
  }
like image 128
Oliv Avatar answered May 31 '26 10:05

Oliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!