2010-03-10 4 views
9

나는 포인터의 벡터를 가지고있다. 모든 요소에 대해 함수를 호출하고 싶습니다. 그러나이 함수는 참조를 취합니다. 요소를 역 참조 할 수있는 간단한 방법이 있습니까?for_each와 boost :: bind를 포인터 벡터로 사용하기

예 :

MyClass::ReferenceFn(Element & e) { ... } 

MyClass::PointerFn(Element * e) { ... } 

MyClass::Function() 
{ 
    std::vector< Element * > elements; 
    // add some elements... 

    // This works, as the argument is a pointer type 
    std::for_each(elements.begin(), elements.end(), 
        boost::bind(&MyClass::PointerFn, boost::ref(*this), _1)); 

    // This fails (compiler error), as the argument is a reference type 
    std::for_each(elements.begin(), elements.end(), 
        boost::bind(&MyClass::ReferenceFn, boost::ref(*this), _1)); 
} 

내가 포인터를 취하는 더러운 래퍼를 만들 수 있습니다,하지만 난이 생각하는 더 좋은 방법이 될했다?

+0

'boost :: ref (* this)'를 사용하는 이유가 있습니까? 난 그냥 사용 : boost :: bind (& MyClass :: ReferenceFn, this, _1) 잘 작동합니다. –

답변

15

당신은 boost::indirect_iterator을 사용할 수

std::for_each(boost::make_indirect_iterator(elements.begin()), 
       boost::make_indirect_iterator(elements.end()), 
       boost::bind(&MyClass::ReferenceFn, boost::ref(*this), _1)); 

그 두번의 operator*에 적응 반복자 역 참조.

+4

+1,이 경우에 나는 BOOST_FOREACH (Element * e, elements) this-> ReferenceFn (* e);를 선호한다. C++은 함수형 언어로 사용할 수 있지만 간결한 * 함수형 언어로는 사용할 수 없습니다. –

+0

그리고 Python은 'for e of elements : self.ReferenceFn (e)'가 될 것입니다. 그것은 가슴 아프다. –

+4

C++ 0x의 경우'for (auto * e : elements) ReferenceFn (* e);'가됩니다. 달콤한 :) –

3

Boost.Lambda 라이브러리를 사용할 수도 있습니다.

// Appears to compile with boost::lambda::bind 
    using namespace boost::lambda; 
    std::for_each(elements.begin(), elements.end(), 
        bind(&MyClass::ReferenceFn, boost::ref(*this), *_1)); 

그러나 나는 BOOST_FOREACH을 선호하는 의견에 동의합니다. for_each "알고리즘"은 실제로 아무런 도움이되지 않습니다. 범위 기반의 for 루프는 훨씬 적은 노력으로 당신을 위해 할 수 있습니다.

관련 문제