[英]How can one write a templated function that takes a generic iterator as a parameter
[英]How can I make a templated function that takes a parameter that is the result of boost::bind?
我有一个辅助方法,它将boost::function<>
类型对象作为输入,并用另一个处理其他逻辑的函子包装该函数。
这是我的签名的样子:
class Example {
public:
typedef ... Callback;
...
template<typename T>
static Callback make_wrapper( const boost::function<void( T )>& );
};
如果我尝试传递 make_wrapper 调用boost::bind
内联的结果,我会收到有关类型不兼容的编译错误(Apple LLVM 7.3.0 版)
class OtherClass {
public:
void method ( uint32_t );
};
OtherClass* other;
Example::Callback c = Example::make_wrapper ( boost::bind( &OtherClass::method, other, _1 ) );
这给出:
error: no matching function for call to 'make_wrapper'
note: candidate template ignored: could not match 'function' against 'bind_t'
我找到了两种解决方法:
温度变量:
boost::function<void( uint32_t )> f = boost::bind( &OtherClass::method, other, _1 ); Example::Callback c = Example::make_wrapper ( f );
调用 make_wrapper 的特定专业化:
Example::Callback c = Example::make_wrapper<uint32_t> ( boost::bind( &OtherClass::method, other, _1 ) );
如果我可以跳过额外的提示并使用内联调用来调用 make_wrapper 以进行绑定,我会更喜欢它。
有没有一种方法可以声明 make_wrapper 模板的签名以帮助编译器找出类型而无需使用上述解决方法之一?
每当您使用bind
您都会丢弃有关绑定函数的参数类型的所有信息。 函数模板不可能推导出参数类型T
,因为bind
的返回值是一个函数对象,可以使用任意数量的任意类型的参数调用。
您可以将bind
函数包装到辅助函数模板中以推导出绑定成员函数,尤其是其结果类型和参数(示例使用std::bind
和std::function
但我相信它可以轻松转换为boost
):
#include <iostream>
#include <string>
#include <functional>
struct foo {
void bar(int a, std::string s) {
std::cout << a << " " << s << std::endl;
}
};
template<typename T1, typename T2>
void make_wrapper(const std::function<void( T1, T2 )>&) {
}
template <class Foo, class Res, class... Args, class... Placeholders>
std::function<Res(Args...)> my_bind(Res (Foo::*bar)(Args...), Foo& f, Placeholders... ps) {
return std::bind(bar, f, ps...);
}
int main() {
foo f;
make_wrapper(my_bind(&foo::bar, f, std::placeholders::_1, std::placeholders::_2));
}
只要foo::bar
没有重载,代码就会工作,在这种情况下,您无法避免static_cast
。
std::bind
和boost::bind
将返回类型列为未指定。 这意味着如果你想要便携,你根本无法知道这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.