Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
И снова, решение использовать нетипизированное сырое хранилище является ограничением для полной реализации обобщённого размеченного объединения на том же уровне, который можно достичь, реализовав его вручную.
Реализация, основанная на сыром хранилище — хотя и оправдывает свою цену — не выдерживает критики, когда её нагружают до предела.Ну не русский это язык, имхо.
static constexpr std::size_t alignment_value = std::max({alignof(Types)...});Я верно понимаю, что в c++14 std::max стало можно использовать в constexpr выражениях?
static_cast<T*>(static_cast<void*>(&_storage))Почему не reinterpret_cast<T*>(&_storage)? Довольно необычная конструкция прежде ее не видел.
Я верно понимаю, что в c++14 std::max стало можно использовать в constexpr выражениях?
Почему не reinterpret_cast<T*>…
The C++ standard guarantees the following:
static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address:
int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);
reinterpret_cast only guarantees that if you cast a pointer to a different type, and then reinterpret_cast it back to the original type, you get the original value. So in the following:
int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);
a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that’s not specified in the standard, and it may not be true on machines with more complex memory systems.
For casting to and from void*, static_cast should be preferred.
a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that’s not specified in the standard, and it may not be true on machines with more complex memory systems.Это утверждение — неправда, смотрите 5.2.10p7 стандарта (он описывает поведение reinterpter_cast):
For casting to and from void*, static_cast should be preferred.
An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void. Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.
Почему не reinterpret_cast<T*>(&_storage)? Довольно необычная конструкция прежде ее не видел.Бытует мненние, что reinterpret_cast небезопасный и страшный, а static_cast добрый и пушистый, и все проверяет. Поэтому будем везде писать static_cast и никогда не столкнемся с ошибками приведения типов.
int main()
{
int x = 5;
//double& y = static_cast<double&>(x); -- does not work :(
//double& y = reinterpret_cast<double&>(x); -- unsafe
double& y = *static_cast<double*>(static_cast<void*>(&x)); // --perfect
std::cout << y << '\n';
}
struct A {};
struct B : public A {};
int main()
{
A x;
B& y = static_cast<B&>(x);
}
P.S. И это... Вы смотрите не туда. :)
Eggs.Variant — Часть I