CAF(C++ actor framework)(序列化之类,无需序列化,直接传)(二)

昨天讲了Struct,还是不够满意,毕竟C++里面类用的比较多嘛,那就先上个类,

这段代码是我稍微改编了一下的结果。都是最基本的用法。

#include <utility>
#include <iostream>
#include <vector>
#include "caf/all.hpp"

using std::cout;
using std::endl;
using std::make_pair;
using std::vector;
using namespace caf;
class foo {

private:
  int a_;
  vector<int> b_;
public:

  foo(int a0 = 0, vector<int> b0 = vector<int>(0)) : a_(a0), b_(b0) { }

  foo(const foo&) = default;

  foo& operator=(const foo&) = default;

  int a() const { return a_; }

  void set_a(int val) { a_ = val; }

  vector<int> b() const { return (vector<int>)b_; }

  void set_b(const vector<int> val){ b_ = val; }
};

bool operator==(const foo& lhs, const foo& rhs) {
  return  lhs.a() == rhs.a()
       && lhs.b() == rhs.b();
}

void testee(event_based_actor* self) {
  self->become (
    [=](const foo& val) {
      aout(self)<< val.a()<<endl;
      auto b = val.b();
      for (auto it = b.begin(); it != b.end(); ++it)
      {
        aout(self)<<*(it)<<endl;
      }
      self->quit();
    }
  );
}

int main(int, char**) {

   //###################First method####################
   announce<foo>("foo", make_pair(&foo::a, &foo::set_a),
                make_pair(&foo::b, &foo::set_b));


  //####################Second method####################
  //a member function pointer to get an attribute of foo
  using foo_getter = int (foo::*)() const;
  using foo_getter1 = vector<int> (foo::*)() const;
  // a member function pointer to set an attribute of foo
  using foo_setter = void (foo::*)(int);
  using foo_setter1 = void (foo::*)(const vector<int>);

  foo_getter g1 = &foo::a;
  foo_setter s1 = &foo::set_a;
  // same is true for b
  foo_getter1 g2 = &foo::b;
  foo_setter1 s2 = &foo::set_b;
  announce<foo>("foo", make_pair(g1, s1), make_pair(g2, s2));


  //####################Third method######################
  // alternative syntax that uses casts instead of variables
  // (returns false since foo is already announced)
  announce<foo>("foo",
               make_pair(static_cast<foo_getter>(&foo::a),
                        static_cast<foo_setter>(&foo::set_a)),
               make_pair(static_cast<foo_getter1>(&foo::b),
                         static_cast<foo_setter1>(&foo::set_b)));
  
  {
    scoped_actor self;
    auto t = spawn(testee);
    self->send(t, foo{1,{2,3}});
  }
  await_all_actors_done();
  shutdown();
  return 0;
}

贴上结果

CAF 告诉我们,你想在消息中传送一个类,你只要告诉它你所有成员的getter 和setter函数,然后呢它提供了三种方式,(一般就选第一种 没有任何区别的 =  = )。

稍微再深入一些的是类里面再套类对象,其实也是很方便。只是多了一个嵌套。可以看github上announce4.cpp

https://github.com/actor-framework/actor-framework/blob/master/examples/type_system/announce_4.cpp

 

还有一个小东西值得一讲,using的用法 

                     using foo_setter1 = void (foo::*)(const vector<int>);

就是声明一个函数指针,指向了foo类里的一个成员函数,参数为一个const 向量,返回值为void。

举一反三,map,pair 都是一样的。只要是C++ 标准的STL都是可以的。

最后还有一篇想讲一下自己对announce5的代码理解和改编吧。

    求粉丝,呵呵呵~

你可能感兴趣的:(CAF(C++ actor framework)(序列化之类,无需序列化,直接传)(二))