我有一些基本上这样做的代码:
struct Base {
virtual ~Base() = default;
virtual int forward() = 0;
};
struct Derived : Base {
int forward() override {
return 42;
}
};
typename std::aligned_storage<sizeof(Derived), alignof(Derived)>::type storage;
new (&storage) Derived{};
auto&& base = *reinterpret_cast<Base*>(&storage);
std::cout << base.forward() << std::endl;
我非常怀疑这是一个定义明确的行为。如果它确实是未定义的行为,我该如何解决?在执行reinterpret_cast
的代码中,我只知道基类的类型。
另一方面,如果在所有情况下都有明确定义的行为,为什么这样做又如何?
仅保留对包含对象的引用不适用于此处。在我的代码中,我想在类型擦除列表中应用SBO,其中类型由我的库的用户创建,并且基本上扩展了Base
类。
我在模板函数中添加元素,但在读取它的函数中,我无法知道Derived
类型。我使用基类的全部原因是因为我只需要在我的代码中使用forward
函数来读取它。
以下是我的代码:
union Storage {
// not used in this example, but it is in my code
void* pointer;
template<typename T>
Storage(T t) noexcept : storage{} {
new (&storage) T{std::move(t)}
}
// This will be the only active member for this example
std::aligned_storage<16, 8> storage = {};
};
template<typename Data>
struct Base {
virtual Data forward();
};
template<typename Data, typename T>
struct Derived : Base<Data> {
Derived(T inst) noexcept : instance{std::move(inst)} {}
Data forward() override {
return instance.forward();
}
T instance;
};
template<typename> type_id(){}
using type_id_t = void(*)();
std::unordered_map<type_id_t, Storage> superList;
template<typename T>
void addToList(T type) {
using Data = decltype(type.forward());
superList.emplace(type_id<Data>, Derived<Data, T>{std::move(type)});
}
template<typename Data>
auto getForwardResult() -> Data {
auto it = superList.find(type_id<Data>);
if (it != superList.end()) {
// I expect the cast to be valid... how to do it?
return reinterpret_cast<Base<Data>*>(it->second.storage)->forward();
}
return {};
}
// These two function are in very distant parts of code.
void insert() {
struct A { int forward() { return 1; } };
struct B { float forward() { return 1.f; } };
struct C { const char* forward() { return "hello"; } };
addToList(A{});
addToList(B{});
addToList(C{});
}
void print() {
std::cout << getForwardResult<int>() << std::endl;
std::cout << getForwardResult<float>() << std::endl;
std::cout << getForwardResult<const char*>() << std::endl;
}
int main() {
insert();
print();
}
答案 0 :(得分:3)
不确定使用基类类型是否需要reinterpret_cast
的确切语义,但您始终可以这样做,
typename std::aligned_storage<sizeof(Derived), alignof(Derived)>::type storage;
auto derived_ptr = new (&storage) Derived{};
auto base_ptr = static_cast<Base*>(derived_ptr);
std::cout << base_ptr->forward() << std::endl;
另外,为什么在代码中使用带有auto&&
引用的base
?
如果您只知道代码中基类的类型,那么考虑在aligned_storage
template <typename Type>
struct TypeAwareAlignedStorage {
using value_type = Type;
using type = std::aligned_storage_t<sizeof(Type), alignof(Type)>;
};
然后您现在可以使用存储对象来获取它所代表的类型
template <typename StorageType>
void cast_to_base(StorageType& storage) {
using DerivedType = std::decay_t<StorageType>::value_type;
auto& derived_ref = *(reinterpret_cast<DerivedType*>(&storage));
Base& base_ref = derived_ref;
base_ref.forward();
}
如果您希望这与完美转发一起使用,那么请使用简单的转发特征
namespace detail {
template <typename TypeToMatch, typename Type>
struct MatchReferenceImpl;
template <typename TypeToMatch, typename Type>
struct MatchReferenceImpl<TypeToMatch&, Type> {
using type = Type&;
};
template <typename TypeToMatch, typename Type>
struct MatchReferenceImpl<const TypeToMatch&, Type> {
using type = const Type&;
};
template <typename TypeToMatch, typename Type>
struct MatchReferenceImpl<TypeToMatch&&, Type> {
using type = Type&&;
};
template <typename TypeToMatch, typename Type>
struct MatchReferenceImpl<const TypeToMatch&&, Type> {
using type = const Type&&;
};
}
template <typename TypeToMatch, typename Type>
struct MatchReference {
using type = typename detail::MatchReferenceImpl<TypeToMatch, Type>::type;
};
template <typename StorageType>
void cast_to_base(StorageType&& storage) {
using DerivedType = std::decay_t<StorageType>::value_type;
auto& derived_ref = *(reinterpret_cast<DerivedType*>(&storage));
typename MatchReference<StorageType&&, Base>::type base_ref = derived_ref;
std::forward<decltype(base_ref)>(base_ref).forward();
}
如果您正在使用类型擦除来创建派生类类型,然后将其添加到同质容器中,您可以执行类似这样的操作
struct Base {
public:
virtual ~Base() = default;
virtual int forward() = 0;
};
/**
* An abstract base mixin that forces definition of a type erasure utility
*/
template <typename Base>
struct GetBasePtr {
public:
Base* get_base_ptr() = 0;
};
template <DerivedType>
class DerivedWrapper : public GetBasePtr<Base> {
public:
// assert that the derived type is actually a derived type
static_assert(std::is_base_of<Base, std::decay_t<DerivedType>>::value, "");
// forward the instance to the internal storage
template <typename T>
DerivedWrapper(T&& storage_in) {
new (&this->storage) DerivedType{std::forward<T>(storage_in)};
}
Base* get_base_ptr() override {
return reinterpret_cast<DerivedType*>(&this->storage);
}
private:
std::aligned_storage_t<sizeof(DerivedType), alignof(DerivedType)> storage;
};
// the homogenous container, global for explanation purposes
std::unordered_map<IdType, std::unique_ptr<GetBasePtr<Base>>> homogenous_container;
template <typename DerivedType>
void add_to_homogenous_collection(IdType id, DerivedType&& object) {
using ToBeErased = DerivedWrapper<std::decay_t<DerivedType>>;
auto ptr = std::unique_ptr<GetBasePtr<Base>>{
std::make_unique<ToBeErased>(std::forward<DerivedType>(object))};
homogenous_container.insert(std::make_pair(id, std::move(ptr)));
}
// and then
homogenous_container[id]->get_base_ptr()->forward();
答案 1 :(得分:2)
你可以简单地做
auto* derived = new (&storage) Derived{};
Base* base = derived;
所以没有reinterpret_cast
。
答案 2 :(得分:0)
在“简单”的例子中,由于你是从派生到基础的,你可以使用static_cast
或dynamic_cast
。
更复杂的用例将以泪流满面,因为基指针的基础值和指向同一对象的派生指针不必相等。它今天可能有用,但明天就失败了:
reinterpret_cast
不能很好地继承,尤其是多重继承。如果您从多个base继承并且第一个基类具有大小(或者如果未执行空基本优化则没有大小),则来自不相关类型的第二个基类的reinterpret_cast
将不应用该偏移。virtual
关键字,并使用模板实现所有内容,一切都会更加简单和正确。static_assert
。