1

I try to write a functor to call a boost function with bind and some template. So i have this main :

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

int main()
{
    Function<int (char)> fb = boost::bind(&function, _1);
    fb('c');
    return (0);
}

and this is my class Function :

template<typename F>
class Function
{
private:
    F       functor;

public:
    Function()
    {
        this->functor = NULL;
    };

    Function(F func)
    {
        this->functor = func;
    };

    template <typename P>
    void    operator()(P arg)
    {
        (*this->functor)(arg);
    };

    void    operator=(F func)
    {
        this->functor = func;
    };
};

i have a problem : when i try to compile i have these errors :

error C2440: 'initializing' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'Function<F>'
IntelliSense: no suitable user-defined conversion from "boost::_bi::bind_t<int, int (*)(char), boost::_bi::list1<boost::arg<1>>>" to "Function<int (char)>" exists  

Someone can help me ?

Adrien A.
  • 441
  • 2
  • 12
  • 31
  • 1
    Read about Type Erasure in C++. Your class doesn't implement it, while `boost::function` and `std::function` in C++11 implement it. I would recommend you to read this article : http://www.artima.com/cppsource/type_erasure.html – Nawaz Dec 17 '11 at 15:26

1 Answers1

0

boost::bind will return something unspecified, but convertible to a boost::function. There is no reason for you to have your own function class.

Look at this simple example:

#include <boost/bind.hpp>
#include <boost/function.hpp>

int func(char) { return 23; }

int main()
{
  boost::function<int(char)> bound = boost::bind(func, _1);
  return 0;
}

What does that unspecified return type mean for your case? You need to erase the type of Function and need to write something called AnyFunction. Why? Because you will never be able to spell out the type of the template argument of Function in C++03 (and even C++11, for e.g. accepting only a specific type as a function argument).

pmr
  • 58,701
  • 10
  • 113
  • 156
  • boost::function is forbidden because i have to write a class who is working with `Function f = &function;` and `Function fb = boost::bind(&function, _1);` – Adrien A. Dec 17 '11 at 15:30
  • I don't get it. You are writing `Function<...>` but someone else is already using it? Why not just use `boost::function`? – pmr Dec 17 '11 at 15:34
  • because it's an exercice and it's forbidden to use this – Adrien A. Dec 17 '11 at 15:38