我可以在不提供参数的情况下生成函数吗? [英] Can I generate a function without providing arguments?
问题描述
因此c ++ 17 具有 std :: function
扣除指南:
So c++17 has std::function
Deduction Guides so given:
int foo();
我可以这样做:
std::function bar(foo);
但是我被困在 c ++ 14 编译器。在那里,我必须做更多的事情: function< int()> bar(foo)
。我想知道是否有一种方法可以创建 std :: function
而不传递函数指针和显式提供函数签名?因此,例如 make_pair
将根据其参数推断出返回类型。我想知道是否可以使用函数编写类似的东西title =显示标记为'c ++ 14'的问题 rel = tag> c ++ 14 ,例如:
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 function
s even using c++14, like:
auto bar = make_function(foo);
这可行吗?
注意:我的真实情况是 foo
是一个模板函数,带有很多我不想推断的参数。因此,我的动机是生成一个函数
而无需提供参数类型。
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.
推荐答案
您的问题最后在精美印刷图中具有某些最重要的部分。如果您的 foo
是模板,则C ++ 17推导指南将无法使用简单的语法来帮助您,例如
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);
您仍然需要为 foo $ c提供模板参数$ c>。假设您可以指定
foo
的参数类型(如您所愿)就可以了,编写make_func的操作很简单:
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);
}
并且比您使用的要多:
auto bar = make_func(&foo<Z, Y, Z>);
这篇关于我可以在不提供参数的情况下生成函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!