【问题标题】:boost::function alike classboost::function 类
【发布时间】:2011-12-17 12:37:38
【问题描述】:

我想实现一个类似于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;
 }

在我的 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
  };

以上代码适用于 Function f = &funct1,
但它不适用于 Function b = boost::bind(&funct1, _1);
我想知道 boost::Function 究竟是如何工作的以及我可以为我的功能支持 boost::bind 做些什么

【问题讨论】:

  • 你是否意识到 boost::function 和 boost::bind 实际上是由纯粹的魔法制成的。重现它们的功能将是一件非常很难的事情。
  • @EthanSteinberg:boost::function 是一个简单的类型擦除应用,一点也不神奇。
  • @Mankarse 我认为 /usr/include/boost/bind/bind.hpp 是 1751 行这一事实不言而喻。
  • @Ethan:这有什么关系?他只说boost::function。他是对的 - 这是类型擦除,仅此而已。
  • 有时是类型擦除,但我认为也有很多捷径(至少在std::function 中)......我自己正在转向“纯魔法”阵营。如果你们都在this Channel9 topic发帖,也许我们可以让STL制作一个关于它的插曲?

标签: c++ boost boost-bind boost-function


【解决方案1】:

我为类型擦除编写了示例程序:http://prograholic.blogspot.com/2011/11/type-erasure.html。在这篇文章中我做了示例类(不幸的是这篇文章是用俄语写的,但我认为代码示例可能会对你有所帮助)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 2016-03-16
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多