1

I would like to realize a class Function similar to boost::function, the class Function can use like this in main.cpp :

#include <iostream>
#include "Function.hpp"

int funct1(char c)
{
   std::cout << c << std::endl;
   return 0;
}

 int main()
 {
   Function<int (char)> f = &funct1;
   Function<int (char)> b = boost::bind(&funct1, _1);
   f('f');
   b('b');
   return 0;
 }

In my Function.hpp, I have

 template <typename T>
 class Function;

 template <typename T, typename P1>
 class Function<T(P1)>
 {
    typedef int (*ptr)(P1);
    public:

    Function(int (*n)(P1)) : _o(n)
   {
   }

   int           operator()(P1 const& p)
   {
     return _o(p);
   }

   Function<T(P1)>&      operator=(int (*n)(P1))
   {
     _o =  n;
     return *this;
   }

  private:
  ptr           _o; // function pointer
  };

Above code works fine for Function f = &funct1,
but it can't work for Function b = boost::bind(&funct1, _1);
I wonder to know how exactly boost::Function works and What can I do to for my Function support boost::bind

  • 1
    Do you realize that boost::function and boost::bind are practically made out of pure magic. Reproducing their functionality is going to be a **very** hard thing to do. –  Dec 17 '11 at 12:53
  • @EthanSteinberg: `boost::function` is a simple application of type erasure, and not very magical at all. – Mankarse Dec 17 '11 at 12:56
  • 1
    @Mankarse I think the fact that /usr/include/boost/bind/bind.hpp is 1751 lines speaks for itself. –  Dec 17 '11 at 12:59
  • 1
    @Ethan: Why is that relevant? He only stated `boost::function`. And he's right- it's type erasure and that's pretty much it. – Puppy Dec 17 '11 at 13:16
  • It's sometimes type erasure, but I think there are plenty of shortcuts, too (at least in `std::function`)... I'm veering towards the "pure magic" camp myself. If you all post on [this Channel9 topic](http://channel9.msdn.com/Forums/TechOff/Advanced-STL-topics) maybe we can make STL make an episode about it? – Kerrek SB Dec 17 '11 at 13:44

0 Answers0