从 "children" 项指针获取 "parent" `std::tuple`

Getting "parent" `std::tuple` from "children" item pointers

struct Apple { };
struct Banana { };
struct Peach { };

using FruitTuple = std::tuple<Apple, Banana, Peach>;

template<typename TTuple, typename TItem>
TTuple& getParentTuple(TItem* mItemPtr)
{
    // <static assert that the tuple item types are unique>
    // ...?
}

int main()
{
    FruitTuple ft;

    // I know these pointers point to objects inside a `FruitTuple`...
    Apple* ptrApple{&std::get<0>(ft)};
    Banana* ptrBanana{&std::get<1>(ft)};
    Peach* ptrPeach{&std::get<2>(ft)};

    // ...is there a way to get the `FruitTuple` they belong to?
    auto& ftFromA(getParentTuple<FruitTuple>(ptrApple));
    auto& ftFromB(getParentTuple<FruitTuple>(ptrBanana));
    auto& ftFromP(getParentTuple<FruitTuple>(ptrPeach));

    assert(&ftFromA == &ftFromB);
    assert(&ftFromB == &ftFromP);
    assert(&ftFromA == &ftFromP);

    return 0;
}

如何getParentTuple<TTuple, TItem>标准兼容非体系结构相关方式实现?

不可能。

编辑:

我认为标准中没有任何内容可以阻止兼容的元组实现在堆上单独分配元素。

然后,元素的内存位置将不允许任何导致元组对象位置的推断。

您唯一可以做的就是扩展您的元素 类 以还包含指向元组的后向指针,然后在将元素放入元组后填充该元组。

以下代码应该适用于常见的实现,但我很确定它不符合标准,因为它假设元组的内存布局是确定的。

在评论中你说你不关心那个案子,所以你开始:

template<typename TTuple, typename TItem>
TTuple& getParentTuple(TItem* mItemPtr)
{
    TTuple dummyTuple;

    // The std::get by type will not compile if types are duplicated, so
    // you do not need a static_assert.
    auto dummyElement = (uintptr_t)&std::get<TItem>(dummyTuple);

    // Calculate the offset of the element to the tuple base address.
    auto offset = dummyElement - (uintptr_t)&dummyTuple;

    // Subtract that offset from the passed element pointer.
    return *(TTuple*)((uintptr_t)mItemPtr - offset);
}

请注意,这只构造了一次元组,在某些情况下可能会产生不需要的副作用或性能影响。我不确定是否有编译时变体。