Can I generate a function without providing arguments?

ぐ巨炮叔叔 提交于 2019-12-18 09:36:15

问题


So c++17 has std::function Deduction Guides so given:

int foo();

I can do:

std::function bar(foo);

But I'm stuck on a c++14 compiler. There I have to do something more like: function<int()> bar(foo). I was wondering if there was a way to create a std::function without passing the function pointer and explicitly providing the function signature? So for example make_pair will deduce the type of it's return from it's arguments. I was wondering if I could write something similar for functions even using c++14, like:

auto bar = make_function(foo);

Is this doable?

Note: My real case is that foo is a template function with a lot of arguments I don't want to deduce. So my motivation here is to generate a function without needing to provide the parameter types.

Live Example


回答1:


Your question has some most important part in the end in the fine print. If your foo is a template, C++17 deduction guides won't help you with a simple syntax like

std::function f(foo);

You'd still need to provide template arguments for foo. Assuming you are OK with specifying foo's argument types (as you have to be) writing make_func is a trivial exercise:

 template<class R, class... ARGS>
 auto make_func(R (*ptr)(ARGS...)) {
      return std::function<R (*)(ARGS...)>(ptr);
 }

And than you use it:

auto bar = make_func(&foo<Z, Y, Z>);


来源:https://stackoverflow.com/questions/54990207/can-i-generate-a-function-without-providing-arguments

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