[英]How to use boost::bind to bind a member-function to ANY object
我正在嘗試通過boost :: bind boost :: function實現某些功能,但是無法使其正常工作。
我看到了如何使用一些參數將對象的成員函數綁定在一起 ,以在以后用作void / void函數。 但是如何將其綁定到任何對象。
我想要一個帶有綁定參數的指向類的成員函數(可以與該類的任何對象一起使用)的指針:
#include "boost/function.hpp"
#include "boost/bind.hpp"
class A
{
public:
A() {}
void func1( int i );
void func2( const std::string& s );
static void dispatch( std::vector<A>& vect, /* boost::function parameter "func" */ ) // what parameter should I set?
{
for ( std::vector<A>::iterator iter = vect.begin();
iter != vect.end();
++iter )
{
// what syntax should I use?
//(*iter).(*func)();
}
}
};
int main()
{
std::vector<A> vect;
// have func1(3) be called for all objects contained in vect
// this does not compile because boost expects an object to bind the function to
A::dispatch( vect, boost::bind( boost::mem_fn(&A::func1), 3 ) );
// have func2("hello") be called for all objects contained in vect
// this does not compile because boost expects an object to bind the function to
A::dispatch( vect, boost::bind( boost::mem_fn(&A::func2), "hello" ) );
}
我嘗試過:
static void dispatch( const std::vector<A>& vect, boost::_mfi::mf0<void, A> func )
...
boost::_mfi::mf1<void,A,int> func( boost::mem_fn(&A::func1) );
boost::_mfi::mf0<void,A> binded( boost::bind( func, 3 ) );
A::dispatch( vect, binded );
但是它無法編譯:
Erreur 1 error C2664: 'boost::_mfi::mf0<R,T>::mf0(void (__thiscall A::* )(void))' : impossible de convertir le paramètre 1 de 'boost::_bi::bind_t<R,F,L>' en 'void (__thiscall A::* )(void)' b:\dev\vobs_bci\public\lib\btle\src\btle\notifierdispatcher.cpp 99
注意:我很遺憾還沒有使用C ++ 11,所以請不要auto
... ;-)
許多細微的調整,大多數的簡化:
Live on Coliru (c ++ 03)
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include <vector>
#include <iostream>
class A
{
public:
A() {}
void func1(int i) const { std::cout << __PRETTY_FUNCTION__ << "(" << i << ")\n"; }
void func2(const std::string& s) const { std::cout << __PRETTY_FUNCTION__ << "(" << s << ")\n"; }
static void dispatch(const std::vector<A>& vect, boost::function<void(A const&)> const& func)
{
for ( std::vector<A>::const_iterator iter = vect.begin();
iter != vect.end();
++iter )
{
func(*iter);
}
}
};
int main()
{
std::vector<A> vect(3);
A::dispatch(vect, boost::bind(&A::func1, _1, 3));
A::dispatch(vect, boost::bind(&A::func2, _1, "hello"));
}
筆記
boost::function<void(A const&)>
因為您取消引用const迭代器 A::dispatch(vect, boost::bind(&A::func1, _1, 3));
標記func1
和func2
const
void func1(int i) const; void func2(std::string const& i) const;
輸出:
void a::func1(int) const(3)
void a::func1(int) const(3)
void a::func1(int) const(3)
void a::func2(const std::string &) const(hello)
void a::func2(const std::string &) const(hello)
void a::func2(const std::string &) const(hello)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.