在C ++ 11之前有类似于std :: function的东西吗? [英] Is there something similar to std::function before C++11?

查看:314
本文介绍了在C ++ 11之前有类似于std :: function的东西吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当C ++ 11不可用时,应该使用什么构造作为 std :: function<> 的代理?

基本上允许从另一个类访问一个类的私有成员函数,就像下面的例子(不使用std :: function的其他功能)。类Foo是固定的,不能改变太多,我只能访问类Bar。

What construct should be used as surrogate for std::function<> when C++11 is not available ?
The alternative should basically allow to access private member functions of one class from another class like in the example below (other features of std::function are not used). Class Foo is fixed and can not be changed much, I have only access to class Bar.

class Foo {
  friend class Bar; // added by me, rest of the class is fixed
  private:

  void doStuffFooA(int i);
  void doStuffFooB(int i);
};

class Bar {
  public:

  Bar( Foo foo, std::function< void (const Foo&, int) > func ) {
    myFoo = foo;
    myFooFunc = func;
  };

  private:

  doStuffBar( const &Foo foo ) {
    myFooFunc( foo, 3 );
  }

  Foo myFoo;
  std::function< void (const Foo&, int) > myFooFunc;
}

int main() {

  Foo foo(...);

  Bar barA( foo, &Foo::doStuffFooA );

  Bar barB( foo, &Foo::doStuffFooB );
  ...
}


推荐答案


在C ++ 11之前有类似于std :: function的东西吗?

Is there something similar to std::function before C++11?

。有Boost.Function( boost :: function<> ),它最近成为C ++标准库的一部分,并为 std :: function<> ;类似地,标准采用Boost.Bind( boost :: bind<>()),并成为 std :: bind< )

Yes. There is Boost.Function (boost::function<>), which lately became part of the C++ Standard Library and provided a reference implementation for std::function<> ; similarly, Boost.Bind (boost::bind<>()) was adopted by the Standard and became std::bind<>().

它实现了一种称为类型擦除的技术,用于保存任何类型的可调用对象。下面是一个可能的,说明性的实现,如何从头开始定义类模板(不要在生产代码中使用,这只是一个例子):

It implements a technique called type erasure for holding callable objects of any type. Here is a possible, illustrative implementation of how such a class template could be defined from scratch (do not use in production code, this is just an example):

#include <memory>

template<typename T>
struct fxn { };

template<typename R, typename... Args>
struct fxn<R(Args...)>
{

public:

    template<typename F>
    fxn(F&& f) 
        : 
        _holder(new holder<typename std::decay<F>::type>(std::forward<F>(f)))
    { }

    R operator () (Args&&... args)
    { _holder->call(std::forward<Args>(args)...); }

private:

    struct holder_base
    { virtual R call(Args&&... args) = 0; };

    template<typename F>
    struct holder : holder_base
    {
        holder(F&& f) : _f(std::forward<F>(f)) { }
        R call(Args&&... args) { return _f(std::forward<Args>(args)...); }
        F _f;
    };

    std::unique_ptr<holder_base> _holder;
};

#include <iostream>

int main()
{
    fxn<void()> f = [] { std::cout << "hello"; };
    f();
}

这篇关于在C ++ 11之前有类似于std :: function的东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆