传递绑定成员函数

pass a bound member function

本文关键字:函数 成员 绑定      更新时间:2023-10-16

我正试图将绑定成员函数传递到例程中,并由模板类确定结果类型:

template< class Fun, class P>
auto splat(double start, double finish, int steps,  Fun fun, double bias)
{
    typedef BOOST_TYPEOF(Fun) Fun_type;
    typedef boost::function_traits<Fun_type> function_traits;
    typedef boost::function_traits<Fun_type>::result_type P;
    vector<P> out = vector<P>(steps);
    double a = steps;
    a = a / 2;
    double step = (finish - start) / (steps - 1);
    double param = start;
    for (int i = 0; i < steps; i++)
    {
        out[i] = fun(param);
        param += step*(1 + accel*(i - a - 1) / (a - 1));
    }
    return out;
}

调用顺序为:

std::function<BallLib::Point(double)> pFun = std::bind(&BallPath::path, one, _1);
Point ppp = pFun(0.0);
vector<Point> line = testspread::splat(0.0, 3.1415, 10, pFun, 0.0);

它无法使用编译严重性代码描述项目文件行错误C2783"std::vector>testspread::splat(double,double,int,Fun,double)":无法推导"P"的模板参数

如何确定p?

在您的签名中

template <class Fun, class P>
auto splat(double start, double finish, int steps, Fun fun, double bias);

您需要一个(不可推导的)类型P(您不使用)。

将代码更改为

template <class Fun>
auto splat(double start, double finish, int steps, Fun fun, double bias)
{
    typedef BOOST_TYPEOF(Fun) Fun_type;
    typedef boost::function_traits<Fun_type> function_traits;
    typedef boost::function_traits<Fun_type>::result_type P;
    vector<P> out(steps);
    const double a = steps / 2;
    const double step = (finish - start) / (steps - 1);
    double param = start;
    for (int i = 0; i < steps; i++)
    {
        out[i] = fun(param);
        param += step*(1 + accel*(i - a - 1) / (a - 1));
    }
    return out;
}

应该解决您的问题。