중첩된 값을 기반으로 하는 인덱스로 다중 인덱스 컨테이너를 강화합니다.

StackOverflow https://stackoverflow.com/questions/1628321

  •  06-07-2019
  •  | 
  •  

문제

다음과 같은 객체가 있는 경우:

struct Bar {
    std::string const& property();
};

다음과 같이 다중 인덱스 컨테이너를 만들 수 있습니다.

struct tag_prop {};
typedef boost::multi_index_container<
    Bar,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_non_unique<
            boost::multi_index::tag<tag_prop>,
            boost::multi_index::const_mem_fun<
                Bar, const std::string&, &Bar::property
            >
        >
    >
    , ... other indexes
> BarContainer;

하지만 다음과 같은 수업이 있다면:

struct Foo {
   Bar const& bar();
};

인덱스를 어떻게 구성할 수 있나요? .bar().property() 컨테이너의 경우 Foo 사물?

일반적으로 나는 호출을 중첩합니다. boost::bind, 그러나 다중 인덱스 컨테이너의 컨텍스트에서 작동하게 하는 방법을 알 수 없습니다.

도움이 되었습니까?

해결책

FOO의 두 인스턴스를 취하는 술어 객체를 만들어야한다고 생각합니다.

같은 것

struct MyPredicate
{

    bool operator() (const Foo& obj1, const Foo& obj2) const
    {
        // fill in here
    }
};

그리고 사용하십시오

...
boost::multi_index::ordered_unique<boost::multi_index::tag<tag_prop>, 
    boost::multi_index::identity<Foo>, MyPredicate>,
...

체크 아웃 Multiindex 주문 지수 참조

다른 팁

사용자 정의 비교기를 제공하는 대신 사용자 정의를 작성할 수 있습니다. 키 추출기:

struct FooBarPropertyExtractor
{
  typedef std::string result_type;
  const result_type& oeprator()(const Foo& f)
  {
    return f.bar().property();
  }
};

...

typedef boost::multi_index_container<
        Bar,
        boost::multi_index::indexed_by<
                boost::multi_index::ordered_non_unique<
                        boost::multi_index::tag<tag_prop>,
                        FooBarPropertyExtractor
                >
        >
        , ... other indexes
> FooContainer;

보다 boost.multiindex 키 추출기의 고급 기능

나는 간단한 일을 하기 위해 람다를 사용하는 것을 좋아하지만 이것은 빠르게 퇴화될 수 있습니다 :)

귀하의 경우에는 좀 더 복잡하기 때문에 자유 함수나 조건자 비교기에 의존하겠습니다.

술어는 유형을 더 명확하게 정의하므로 일반적으로 실제로 가져오기가 더 쉽다는 장점이 있습니다.

또한 가독성을 위해 일반적으로 인덱스를 형식 정의하여 다음을 제공합니다.

namespace mi = boost::multi_index;

struct FooComparator
{
  bool operator()(Foo const& lhs, Foo const& rhs) const
  {
    return lhs.bar().property() < rhs.bar().property();
  }
};

typedef mi::ordered_unique <
          mi::tag<tag_prop>,
          mi::identity<Foo>,
          FooComparator
        > foo_bar_index_t;

typedef boost::multi_index_container <
          Foo,
          mi::indexed_by < 
            foo_bar_index_t,
            // ... other indexes
          >
        > foo_container_t;

조건자 접근 방식에는 더 많은 상용구 코드가 필요하지만 컨테이너 정의 자체와 분리된 인덱스 정의에서 비교 논리를 훌륭하게 분리할 수 있습니다.

명확한 분리로 인해 구조를 한 눈에 쉽게 볼 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top