如何使对模板函数的调用不那么冗长 [英] How to make a call to a template function less verbose

查看:26
本文介绍了如何使对模板函数的调用不那么冗长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个功能

template <class ...T>
void foo(std::function<void(T...)> callback);

我向其中传递了一个回调.

into which I pass a callback.

我想做类似的事情

foo(bar);

其中 bar 是,例如,

void bar(int a, long b, double c, float d);

但这给了我

error: no matching function for call to bar(void (&)(int, long int, double, float))

我必须将 foo 称为

foo(std::function<void(int, long, double, float)>(bar));

太啰嗦了.甚至

foo<int, long, double, float>(bar);

本来会更好.

foo(bar);

会很理想.

无论如何,我怎样才能使对 foo 的调用不那么冗长?

Anyway, how can I make calls to foo to be less verbose?

foo 的声明必须保持不变.

declaration of foo has to stay the same.

推荐答案

我会写一个包装函数,将函数指针转换成一个 std::function 包装器:

I'd write a wrapper function that translates the function pointer into a std::function wrapper:

template <typename... T>
void foo(std::function<void (T...)> f) {}

template <typename... T>
void foo(void (*f)(T...)) {
    foo(std::function<void (T...)>(f));
}

foo() 然后可以通过任何一种方式调用:

foo() can then be called either way:

void bar(int,double) {}

void foo_caller() {
    foo(std::function<void (int,double)>(bar));
    foo(bar);
}

附录:非静态成员函数包装器

同样的方法可用于指向成员函数的指针——只需添加另一个重载:

Same approach can be used for pointer-to-member functions — just add another overload:

template <typename C,typename... T>
void foo(void (C::*f)(T...)) {
    foo(std::function<void (C *,T...)>(f));
}

注意成员函数的 this 指针的额外第一个参数.用法类似:

Note the extra first parameter for the this pointer for the member function. Usage is similar:

struct quux {
    void mf(char *,double) {}
};

void foo_caller() {
    foo(&quux::mf);
}

这篇关于如何使对模板函数的调用不那么冗长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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