对于下面的类,我如何表示指向 Bar
实例之一的成员变量 qux
的指针?
struct Foo {
struct Bar {
int qux;
} bar1, bar2;
};
当我使用boost::multi_index
容器并且需要使用qux
作为 key 时需要这个,这在 key 提取器中是需要的
template<class Class,typename Type,Type Class::*PtrToMember>
struct boost::multi_index::member
最佳答案
我假设其目的是创建一个包含 Foo
的 boost multi_index 容器,并使用 qux
作为键。虽然 qux
不是 Foo
的成员,但您可以通过索引成员 Foo::bar1
并提供自定义比较谓词来实现这一点对于有序索引。例如,如果您尝试创建一个 ordered_unique
键,您可以这样写:
ordered_unique<member<Foo, Foo::Bar, &Foo::bar1>, compare_foo_bar>
其中 compare_foo_bar
是 Foo::Bar
的友元,根据需要定义:
struct compare_foo_bar
{
bool operator()(const Foo::Bar& lhs, const Foo::Bar& rhs)
{
return lhs.qux < rhs.qux;
}
};
关于c++ - 指向嵌套结构中成员变量的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538430/