繁体   English   中英

将方法传递给包含对象指针的集合的所有元素,C ++

[英]Passing methods to all elements of a set containing object pointers, C++

我有一个类,该类派生自包含指向另一个类的对象的指针的集合。 基本上看起来像这样:

class connectionSLOT: private std::set<connectionSLOT*>
{
...
};

这非常简单,并且可以很好地表示(有向)图。 我的课程还包含一些简单的方法,例如connect(),disconnect()等,它们都希望将对象指针作为参数,并且还带有此类指针。 (即,它们的声明仅在名称上有所不同)例如:

connectionSLOT* connectionSLOT::connect(connectionSLOT *A)
{
  insert (A); return A;
}

要么:

connectionSLOT* connectionSLOT::disconnect(connectionSLOT *A)
{
  erase(A); return this;
}

所以,我的问题是:我该如何创建一个不将这些函数应用于对象本身而不是对象集中包含的所有对象(即调用对象中包含的对象)的新方法?

我想要这样的东西:

connectionSLOT* new_method( 'passing a method (and its argument) ' )
{
  for(it=begin();it!=end();++it) 'execute the method on (*it)' ;
  return something;
} 

也许可以将其用于将所有相邻点连接到某个顶点。 但是由于new_method()本身也是一个适当的函数,因此也可以传递它:

int main()
{
  // ... here declaring some objects and connection amongst them...

  A->new_method( new_method( disconnect(B) ) ) ;

/* calling new_method() recursively to disconnect all the vertices from B which ones are
    reachable from A in two steps */

...
}

我希望可以以某种方式做。 (语法基本上不重要)提出任何建议都值得赞赏。

罗伯特

可以使用C ++ 11吗? 我相信,您正在寻找std::function和lambda表达式。

void DoSth(std::function<void(void)> fn)
{
    fn();
}

DoSth([]() { printf("Hello, world!\n"); });

您的代码看起来更像以下代码:

connectionSLOT::new_method(std::function<void(connectionSlot *)> fn)
{
    for (it = begin(); it != end(); ++it)
        fn(*it);

    return something;
} 

int main()
{
    // ... here declaring some objects and connection amongst them...

    A->new_method([](connectionSlot * B) { disconnect(B); } );

    // ...
}

暂无
暂无

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

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