Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c++ - Can I generate a function without providing arguments?

So has std::function Deduction Guides so given:

int foo();

I can do:

std::function bar(foo);

But I'm stuck on a 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 , 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...