简体   繁体   English

boost :: function like class

[英]boost::function alike class

I would like to realize a class Function similar to boost::function, the class Function can use like this in main.cpp : 我想实现一个类似于boost :: function的类Function,该类Function可以在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 在我的Function.hpp中,我有

 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, 上面的代码适用于功能f =&funct1,
but it can't work for Function b = boost::bind(&funct1, _1); 但不适用于功能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 我想知道boost :: Function是如何工作的,如何为我的Function支持boost :: bind做些什么

I wrote sample program for type erasure: http://prograholic.blogspot.com/2011/11/type-erasure.html . 我编写了用于类型擦除的示例程序: http : //prograholic.blogspot.com/2011/11/type-erasure.html In this article I made sample class (unfortunately this article written in Russian, but I think that code samples may help you) 在本文中,我制作了示例类(不幸的是,本文是用俄语编写的,但是我认为代码示例可能会对您有所帮助)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM