微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c 11:模板化包装功能

我尝试创建一个通用包装函数,它将任何函数作为参数以及它们的参数.就像std :: thread构造函数一样.

我目前的代码是:

#include <iostream>

using namespace std;

template<typename FUNCTION,typename... ARGS>
void wrapper(FUNCTION&& func,ARGS&&... args)
{
    cout << "WRAPPER: BEFORE" << endl;
    auto res = func(args...);
    cout << "WRAPPER: AFTER" << endl;
    //return res;
}

int dummy(int a,int b)
{
    cout << a << '+' << b << '=' << (a + b) << endl;
    return a + b;
}

int main(void)
{
    dummy(3,4);
    wrapper(dummy,3,4);
}

包装函数本身有效.它使用给定的参数调用给定的函数对象(std :: function,functor或只是“普通”函数).但我也想返回它的返回值.

这应该与删除的return语句一起使用,但不幸的是我不知道如何声明包装函数返回类型.

我尝试了很多东西(例如使用decltype),但没有任何效果.我现在的问题是,如何运行以下代码

#include <iostream>

template<typename FUNCTION,typename... ARGS>
??? wrapper(FUNCTION&& func,ARGS&&... args)
{
    cout << "WRAPPER: BEFORE" << endl;
    auto res = func(args...);
    cout << "WRAPPER: AFTER" << endl;
    return res;
}

int dummy(int a,4);
    cout << "WRAPPERS RES IS: " << wrapper(dummy,4) << endl;
}

我认为代码应该工作,除了???.

谢谢你的任何想法

问候
凯文

解决方法

使用 std::result_of
template <typename F,typename ...Args>
typename std::result_of<F &&(Args &&...)>::type wrapper(F && f,Args &&... args)
{
    return std::forward<F>(f)(std::forward<Args>(args)...);
}

在C 14中,您可以使用result_of_t别名:

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

或者您可以使用返回类型扣除:

template <typename F,typename ...Args>
decltype(auto) wrapper(F && f,Args &&... args)
{
    std::cout << "before\n";
    auto && res = std::forward<F>(f)(std::forward<Args>(args)...);
    std::cout << "after\n";
    return res;
}

原文地址:https://www.jb51.cc/c/116826.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐