无法添加完美转发到包装函数 [英] Can't add perfect forwarding to wrapper function

查看:195
本文介绍了无法添加完美转发到包装函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答此问题时,我写了此工作代码,模板参数中传递的包装函数:

While answering this question I wrote this working code, wrapping function passed in template arguments:

template<typename Fn, Fn fn, typename... Args>
auto wrapper(Args... args)->decltype(fn(args...)){
    return fn(args...);
}
#define WRAPPER(FUNC) wrapper<decltype(&FUNC), &FUNC>

使用示例(我使用此代码进行测试):

Example usage (I use this code for testing):

int min(int a, int b){
    return (a<b)?a:b;
}

#include<iostream>
using std::cout;
int main(){
    cout<<WRAPPER(min)(10, 20)<<'\n';
}

两个人告诉我使用完美转发。当我问如何做到这一点,其中一个重定向我在这里。我阅读问题,仔细阅读最佳答案,并将 wrapper 更改为:

Two people told me to use perfect forwarding. When I asked how to do this, one of them redirected me here. I read question, carefully read best answer, and changed wrapper to:

#include<utility>
template<typename Fn, Fn fn, typename... Args>
auto wrapper(Args&&... args)->decltype(fn(std::forward<Args...>(args...))){
    return fn(std::forward<Args...>(args...));
}

它编译,除非我尝试使用上面的示例代码检查。 如何修复代码?

It compiles, unless I attempt to check it out using example code above. How can I fix the code?

http://rextester.com/YUIYI99787

推荐答案

您在return语句中的错误位置有点。您想要:

You have the dots in the wrong place on the return statement. You want:

return fn(std::forward<Args>(args)...);

这将扩展为:

return fn(std::forward<T1>(t1), std::forward<T1>(t2), ...);

您写的内容将扩展为:

return fn(std::forward<T1,T2,...>(t1, t2, t3)); 

诀窍是每次你看到...,认为它会复制后面的东西它。这可能会很棘手,因为有各种各样的方式来构建背后的事情,包括能够做一个交叉产品等。

The trick is that everytime you see "...", think "it will replicate the thing behind it". This can get tricky because there are all sorts of ways to construct the "thing behind it", including being able to do a cross-product and the like.

这篇关于无法添加完美转发到包装函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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