将模板函数作为普通函数的参数传递 [英] Passing template function as argument for normal function

查看:63
本文介绍了将模板函数作为普通函数的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将模板函数(或其他函数)作为参数传递给第二个函数(不是模板).向Google询问这似乎只会提供相反的信息(作为模板参数传递的函数)

I'm wondering if it's possible to pass a template function (or other) as an argument to a second function (which is not a template). Asking Google about this only seems to give info about the opposite ( Function passed as template argument )

我可以找到的唯一相关页面是 http://www.beta.microsoft.com/VisualStudio/feedbackdetail/view/947754/compiler-error-on-passing-template功能作为带有省略号的功能的争论(不是很有帮助)

The only relevant page I could find was http://www.beta.microsoft.com/VisualStudio/feedbackdetail/view/947754/compiler-error-on-passing-template-function-as-an-argument-to-a-function-with-ellipsis (not very helpful)

我期望的是类似的东西

template<class N>void print(A input){cout << input;}
void execute(int input, template<class N>void func(N)){func(input)}

然后再致电

execute(1,print);

那么,可以这样做还是必须为execute()定义另一个模板?

So, can this be done or would another template have to be defined for execute() ?

推荐答案

函数模板表示一个无限重载集,因此,除非您具有与专业化兼容的目标类型,否则推导函数类型总是失败.例如:

Function templates represent an infinite overload set, so unless you have a target type that is compatible with a specialization, deduction of the function type always fails. For example:

template<class T> void f(T);
template<class T> void h(T);

void g() {
    h(f); // error: couldn't infer template argument 'T'
    h(f<int>); // OK, type is void (*)(int)
    h<void(int)>(f); // OK, compatible specialization
}

从上面我们可以看到程序的有效性要求我们为函数模板指定模板参数,通常,指定它们并不总是很直观.相反,您可以将 print 用作仿函数,并使用泛型的重载调用运算符作为额外的间接访问级别:

From above we can see that the validity of the program demands that we specify the template arguments for the function template, when in general it isn't always intuitive to specify them. You can instead make print a functor with a generic overloaded call operator as an extra level of indirection:

struct print {
     template<typename T>
     void operator()(T&& x) const {
         std::cout << x;
     }
};

现在,您可以让 execute 接受任何Callable并使用输入来调用它:

Now you can have execute accept any Callable and invoke it with the input:

template<class T, class Op>
void execute(T&& input, Op&& op) {
    std::forward<Op>(op)(std::forward<T>(input));
}

void g() { execute(1, print{}); }

通用lambdas(C ++ 14)使这一点更加简洁:

Generic lambdas (C++14) make this a lot more concise:

execute(1, [] (auto&& x) { std::cout << x; });

这篇关于将模板函数作为普通函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆