2013-03-25 2 views
1

다른 클래스의 개체에 대한 포인터가 들어있는 집합에서 파생 된 클래스가 있습니다.개체 포인터가 포함 된 집합의 모든 요소에 메서드 전달 C++

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

그것은 매우 간단 아마도, (감독) 그래프를 나타낼 잘 작동 : 은 기본적으로는 다음과 같습니다. 내 클래스에는 connect(), disconnect() 등과 같은 간단한 메소드가 포함되어 있으며, 모두 객체 포인터를 인자로 기대하며 이러한 포인터로 리턴한다. 은 (자신의 선언은 이름 만 다를 IE) 예를 들어 :

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 */ 

... 
} 

I 희망, 어떻게 든 할 수 있습니다. (구문은 기본적으로 중요하지 않습니다.) 제안을하는 것이 좋습니다.

로버트

답변

0

C++ 11을 사용할 수 있습니까? 나는 그, std::function과 람다식이 당신이 찾고있는 것이라고 믿습니다.

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); }); 

    // ... 
} 
+0

와우! 빠른 답변 주셔서 감사합니다! 예, 저는 그 버전을 (gnu C++ 컴파일러로) 사용합니다. 그리고 여러분의 솔루션은 꼭 필요한 것입니다! :) 정말 고맙습니다! –

관련 문제