How to use an overloaded function as an argument to a function template?

I think everyone has experience with code like the one below:

void fun(Type1&);
void fun(Type2&);
vector<Type1> vec;
for_each(vec.begin(), vec.end(), fun);

Of course, this does not compile, because it is not clear which function to pass. And what is your commonly used solution to the problem?

I know this will work:

for_each(vec.begin(), vec.end(), (void(*)(Type1&))fun);

But any better ideas?

+3
source share
2 answers

One solution is to use a template function:

template<typename T>
void fun(T&);
// specialize fun for Type1 and Type2
...
for_each(vec.begin(), vec.end(), fun<Type1>);

It is best to use a functor with a pattern operator():

struct fun
{
  template<typename T>
  void operator()(T&) const;
};
...
for_each(vec.begin(), vec.end(), fun()); // T for operator() will be deduced automatically
+2
source

. fun() ( ), . .

++ C:

for_each(vec.begin(), vec.end(), reinterpret_cast<void(*)(Type1&)>(fun));

static_cast :

for_each(vec.begin(), vec.end(), static_cast<void(*)(Type1&)>(fun));

.

, - , C-.

:

for_each<std::vector<A>::iterator, void(*)(Type1&)>(vec.begin(), vec.end(), fun);

- . , .

0

Source: https://habr.com/ru/post/1749885/


All Articles