wayne
发表于 2010-8-5 13:35:58
functional实际上一个类对象,竟然可以转化为函数指针吗?难道是实现里面提供了转为指针的操作符?
mathe 发表于 2010-8-5 12:00 http://bbs.emath.ac.cn/images/common/back.gif
functors可以是:
* class object with operator()
* function pointer
* member function pointer
wayne
发表于 2010-8-5 13:45:36
关于 重载函数的bind问题,boost官网给了两种解决办法,呵呵,前面都提到过。
http://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html#err_overloaded
Binding an overloaded function
An attempt to bind an overloaded function usually results in an error, as there is no way to tell which overload was meant to be bound. This is a common problem with member functions with two overloads, const and non-const, as in this simplified example:
struct X
{
int& get();
int const& get() const;
};
int main()
{
boost::bind( &X::get, _1 );
}
The ambiguity can be resolved manually by casting the (member) function pointer to the desired type:
int main()
{
boost::bind( static_cast< int const& (X::*) () const >( &X::get ), _1 );
}
Another, arguably more readable, alternative is to introduce a temporary variable:
int main()
{
int const& (X::*get) () const = &X::get;
boost::bind( get, _1 );
}
wayne
发表于 2010-8-5 14:37:08
21# wayne
写了一个 Demo code:#include <iostream>
#include <algorithm>
#include <vector>
#include <tr1/functional>
using std::tr1::placeholders::_1;
//normal function
void foo(int i) { std::cout<<"Foo\t"<<i<<std::endl; }
//class object with operator()
class Bar{
public:
void operator () (int i) { std::cout<<"Bar\t"<< i<<std::endl; }
};
//member function
class Ctest {
public:
void puts(std::string &s) {std::cout<<"STRING:\t"<<s<<std::endl;}
void puts(double x) {std::cout <<"DOUBLE:\t"<<x<<std::endl;}
};
int main(){
Bar bar;Ctest fm;
std::tr1::function<void (int)> f(&foo); f(2009);
std::tr1::function<void (int)> b=bar; b(2010);
double a = { .8, .7, .9, .5, .3};
std::vector<double> v(a,a+5);
sort(v.begin(),v.end());
void (Ctest::*fn)(double) = &Ctest::puts;
std::for_each(v.begin(), v.end(), std::tr1::bind(fn, fm, _1));
}