C++ c++;11:模板包装函数

C++ c++;11:模板包装函数,c++,templates,c++11,wrapper,functor,C++,Templates,C++11,Wrapper,Functor,我试图创建一个通用的包装函数,它接受任何函数作为参数,也接受它们的参数。就像std::thread构造函数一样 我目前的代码是: #include <iostream> using namespace std; template<typename FUNCTION, typename... ARGS> void wrapper(FUNCTION&& func, ARGS&&... args) { cout << "W

我试图创建一个通用的包装函数,它接受任何函数作为参数,也接受它们的参数。就像
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);
}
我认为代码应该可以工作,除了

谢谢你的建议

问候 凯文

使用:

或者您可以使用退货类型扣减:

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;
}
模板
decltype(自动)包装器(F&&F,Args&&…Args)
{

std::cout您可以对C++11自动跟踪返回类型使用
decltype

template<typename FUNCTION, typename... ARGS>
auto wrapper(FUNCTION&& func, ARGS&&... args) -> decltype(func(std::forward<ARGS>(args)...))
模板
自动包装器(函数&&func,参数&&…参数)->decltype(func(标准::forward


在C++14中,只需执行以下操作:

template<typename FUNCTION, typename... ARGS>
decltype(auto) wrapper(FUNCTION&& func, ARGS&&... args)
模板
decltype(自动)包装器(函数和函数、参数和…参数)

我不知道
->
的语法。谢谢你。它起作用了:)!你应该这样传递:
func(std::forward(args)…。
@Smith\u 61:很好。这起作用了:)非常感谢。不幸的是,我不知道
result\u。在C++14中,您也可以完全忘记
和朋友的
result\u,并使用返回类型推断:)在
F&(Args&&&…)中使用
&
做什么
do btw?@0x499602D2:它按照框上的说明执行。它提供的类型与以后实际调用中使用的类型相同。您不需要将整个
std::forward
shebang也用于尾部返回类型,以免您使用错误的
func
重载或其他类型的返回类型吗?谢谢您的回答。它很有效太好了:)也感谢c++14版本。
Kerrek SB
首先给出了一个工作版本,所以我将他的帖子标记为已接受。但也感谢你!(你也得到了投票)@Praetorian是的,我们确实需要更新“shebang”,谢谢你的留言。
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;
}
template<typename FUNCTION, typename... ARGS>
auto wrapper(FUNCTION&& func, ARGS&&... args) -> decltype(func(std::forward<ARGS>(args)...))
template<typename FUNCTION, typename... ARGS>
decltype(auto) wrapper(FUNCTION&& func, ARGS&&... args)