与std :: bind相反,为函数添加伪参数

Lal*_*and 11 c++ bind function

我需要与std :: bind相反的东西,它将伪参数添加到函数签名而不是boost :: bind如何绑定参数.

我有这个功能:

std::function<void (void)> myFunc;
Run Code Online (Sandbox Code Playgroud)

但是我想把它转换成一个std::function<void(int)>传递给这个函数

void processFunction( std::function<void(int)> func);
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 6

编辑 哦,我在聊天中提到了显而易见的事:

@EthanSteinberg:lambdas?

[] (int realparam, int dummy) { return foo(realparam); }
Run Code Online (Sandbox Code Playgroud)

但它被驳回了,这就是为什么我跳到:

编辑我刚刚实现了一个更简单的方法:http://ideone.com/pPWZk

#include <iostream>
#include <functional>
using namespace std::placeholders;

int foo(int i)
{
    return i*2;
}

int main(int argc, const char *argv[])
{
    std::function<int(int, int)> barfunc = std::bind(foo, (_1, _2));
    std::cout << barfunc(-999, 21) << std::endl;

    // or even (thanks Xeo)
    barfunc = std::bind(foo, _2);
    std::cout << barfunc(-999, 21) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Variadic模板http://ideone.com/8KIsW

基于可变参数模板的更长的答案将导致调用站点上的代码可能更小(如果您想用长参数列表包装函数).

#include <iostream>
#include <functional>

int foo(int i)
{
    return i*2;
}

template <typename Ax, typename R, typename... A>
struct Wrap
{
    typedef R (*F)(A...);
    typedef std::function<R(A...)> Ftor;

    Wrap(F f) : _f(f) { }
    Wrap(const Ftor& f) : _f(f) { }

    R operator()(Ax extra, A... a) const
    { return _f(a...); /*just forward*/ }

    Ftor _f;
};

template <typename Ax=int, typename R, typename... A>
std::function<R(Ax, A...)> wrap(R (f)(A...))
{
    return Wrap<Ax,R,A...>(f);
}

template <typename Ax=int, typename R, typename... A>
std::function<R(Ax, A...)> wrap(std::function<R(A...)> functor)
{
    return Wrap<Ax,R,A...>(functor);
}

int main(int argc, const char *argv[])
{
    auto bar = wrap(foo);
    std::function<int(int, int)> barfunc = wrap(foo);

    std::cout << barfunc(-999, 21) << std::endl;

    // wrap the barfunc?
    auto rewrap = wrap(barfunc);
    std::cout << rewrap(-999, -999, 21) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由此推广将需要更多繁重的工作.我想我已经在过去的帮助器中看到'剖析'(使用元编程)std :: function <>的签名,你应该能够识别非void函数,甚至可能添加参数在结尾或中间(据我所知,现在很棘手).

但是对于OP中的简单案例,看起来你已经被覆盖了