Is it good approach to “pass” function template as

2019-04-11 15:58发布

问题:

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);
}

Demo

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)

回答1:

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)...);}

GCC was broken with generic stateless lambdas, so you had to add at least minimal state like [dummy=nullptr] or something like that. Luckily they fixed it.



回答2:

It is fine, except you would probably want to enable perfect forwarding:

#define PASS_TEMPLATE(name) [](auto&&... args){return name(std::forward<decltype(args)>(args)...);}