Обратный указатель на элемент данных

Привет я пытаюсь выяснить, является ли законным (по C ++) стандарт для вычисления смещения члена класса (для того, чтобы обратить его).

class A
{
public:
int a, b, c, d;
};

template <typename ParentClass, typename T>
ParentClass const * offset_this_pointer(T const * member_ptr, T ParentClass::* offset)
{
ParentClass const * parent_p = nullptr;
// we are technically dereferencing a NULL pointer here,
// but we are not using the result, only taking the address of it
// This works and yields the desired result in MSVC 2010, gcc 4.9.2 and Solaris10 compilers.
T const * offset_p = &(parent_p->*offset);

return reinterpret_cast<ParentClass const *>((uintptr_t)member_ptr - (uintptr_t)(offset_p));
}

int main()
{
A a;

assert(&a == offset_this_pointer(&a.b, &A::b)); // passes

return 0;
}

Законно ли C ++ делать &(parent_p->*offset) с parent_p быть nullptr?

1

Решение

Это обсуждалось в течение некоторого времени без видимого результата. Тем не менее, дебаты спорят с предоставленной реализацией, благословенной стандартом offsetof макро.

2

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector