Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass multiple function overloads as a single argument?

This is another case of trying to get rid of a macro. Consider

void f_(int i) { printf("f_(int)\t%d\n", i); }
void f_(int i, double x) { printf("f_(int, double)\t%d, %5.3f\n", i, x); }
void g_(int i) { printf("g_(int)\t%d\n", i); }
void g_(int i, double x) { printf("g_(int, double)\t%d, %5.3f\n", i, x); }

(Imagine f_() gets data form a .foo file or uses hard-coded "dummy" values, g_() does the same for .bar.) There might be a function to decide which overload to call:

void f(int i, double d) { (i > 0) ? f_(i, d) : f_(i); }

with the same logic duplicated for g_():

void g(int i, double x) { (i > 0) ? g_(i, x) : g_(i); }

Getting rid of that duplicated code is easy with a macro:

#define h(i, x, func_) (i > 0) ? func_(i, x) : func_(i);
// ...
h(-1, 314.1, f_);
h(99, 314.1, f_);
h(-1, 314.1, g_);
h(99, 314.1, g_);

But of course we'd rather not use macros in C++. The "obvious" template

template<typename T>
void h2(int i, double x, T t)
{
   (i > 0) ? t(i, x) : t(i);
}
// ...
h2(-1, 314.1, f_);

fails because the compiler can't figure out what overload of f_() to use.

How can I replace the functionality of the macro h?

like image 558
Ðаn Avatar asked Aug 14 '18 13:08

Ðаn


1 Answers

You can use a variadic lambda and have the lambda call the function you wish to call.

template<typename T>
void h2(int i, double x, T t)
{
   i > 0 ? t(i, x) : t(i);
}

int main()
{
    h2(-1, 314.1, [](auto... args){ f_(args...); });
    //                              ^^ change this to g_ if you want to use g_ instead of f_
}
like image 102
NathanOliver Avatar answered Sep 20 '22 17:09

NathanOliver