[英]C++ - Creating pointers to elements of an array containing pointers to class objects
[英]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.