Black Moses Black Moses - 1 year ago 70
C++ Question

Is it good approach to "pass" function template as generic-variadic lambda return statement?

I was having fun with attempts to pass function template as

template template
argument. Of course C++ doesn't allow passing function templates this way. But I came up with simple hax:

#include <iostream>

#define PASS_TEMPLATE(name) [](auto&... args){return name(args...);}

template <typename T, typename S>
void function_template(T t, S s) {std::cout << t << ' ' << s << std::endl;}

template <typename Hax, typename T, typename S>
auto test(Hax hax, T t, S s)
return hax(t, s);

int main()
test(PASS_TEMPLATE(function_template), 1, 1.5);


The question is:

  • Is this viable approach? (Is it safe? No corner cases?)

  • Is it universal, or are there cases that will cause compilation to fail?

  • Are there other alternatives to achieve this? (I know some people don't like macros)

I was testing this only on GCC 6.1.0 (I really hope it's not GCC extension or something)

Answer Source

I recommend using perfect forwarding, but aside from that it's a perfectly viable (and probably the only aside from manually typing it all) approach to the problem.

So, that would be:

#define PASS_TEMPLATE(name) [](auto&&... args){return name(decltype(args)(args)...);}

Be aware that GCC is broken with generic stateless lambdas, so you have to add at least minimal state like [dummy=nullptr] or something like that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download