可变模板,函数作为参数 [英] Variadic template, function as argument

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

问题描述

我想在可变参数模板中使用函数作为参数,为什么以下不起作用?我如何使它工作?

I would like to use a function as argument in a variadic template, why does the following not work? How do I make it work?

template<typename F, typename... Args>
F test(F f, const Args&&... args) {
return f(std::forward<Args>(args)...);
}

int simple(int i) { 
    return i; 
}


int main()
{
    std::cout << test(simple, 2); // error, 'std::forward': none of the 2 overloads could convert all the argument types
}

推荐答案

您的代码存在一些问题.

There are a couple of problems with your code.

首先,您应该使用转发引用,因此您需要将const Args&&... 更改为Args&&....

First of all, you should use forwarding references, so you need to change const Args&&... to Args&&....

那么,test 不必返回 F.所以这里使用decltype(auto)是合理的.

Then, test does not have to return F. So it is reasonable to use decltype(auto) here.

除此之外,转发 f 也是有意义的.

In addition to that, it makes sense to forward f too.

固定版本可能如下所示:

The fixed version might look like this:

template<typename F, typename... Args>
decltype(auto) test(F&& f, Args&&... args) {
    return std::forward<F>(f)(std::forward<Args>(args)...);
}

WANDBOX 示例

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

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