解决此问题的最佳方法是提供您自己的用户定义的密钥提取器。请注意,变体类型派生自一个公共基础这一事实在这里没有任何重要作用:在没有继承的情况下,只需应用一个常规访问者来处理变体中的所有类型(如果所有类型都符合获取密钥的相同语法)。
Live Coliru Demo
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/variant/variant.hpp>
#include <utility>
struct base
{
virtual ~base()=default;
virtual std::pair<char,char> extractKey()const=0;
};
struct derived1:base
{
std::pair<char,char> extractKey()const override{return{1,0};};
};
struct derived2:base
{
std::pair<char,char> extractKey()const override{return{0,1};};
};
using namespace boost::multi_index;
using variant=boost::variant<derived1,derived2>;
struct variant_key
{
using result_type=std::pair<char,char>;
auto operator()(const variant& x)const
{
return boost::apply_visitor(
[](const base& b){return b.extractKey();},
x
);
}
};
using container=multi_index_container<
variant,
indexed_by<
ordered_non_unique<variant_key>
>
>;
// testing
#include <iostream>
template<typename... Ts> struct overloaded:Ts...{using Ts::operator()...;};
template<typename... Ts> overloaded(Ts...)->overloaded<Ts...>;
int main()
{
container c;
for(int i=2;i--;){
c.insert(variant(derived1()));
c.insert(variant(derived2()));
}
for(const auto& x:c){
boost::apply_visitor(
overloaded{
[](const derived1&){std::cout<<"derived1 ";},
[](const derived2&){std::cout<<"derived2 ";}
},
x
);
}
}
输出
derived2 derived2 derived1 derived1