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

  • A+
Category:Languages

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?

 


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_ } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: