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

陌路散爱 提交于 2019-12-12 08:58:08

问题


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


来源:https://stackoverflow.com/questions/39933137/is-it-good-approach-to-pass-function-template-as-generic-variadic-lambda-retur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!