【发布时间】:2021-11-25 08:10:34
【问题描述】:
是否可以在std::atomic_ref<T> 和std::atomic_ref<U> 之间向下转换,其中U 是T 的子类?
我尝试了以下代码,但没有成功。
template<typename T>
std::atomic_ref<T> World::getComponentByID(componentInstanceId uuid) const {
static componentTypeId key = stringHash(typeid(T).name());
return components.at(uuid);
}
模板参数T 是位置(Component 的子类)。 components 是 componentInstanceIds 到 Components 的映射。
error C2440: 'return': cannot convert from 'const std::atomic_ref<Component>' to 'std::atomic_ref<Position>
【问题讨论】:
-
我认为您的意思是“向上转型”而不是“向下转型”?
-
我正在从超类
Component转换为子类Position@ruakh。 -
我明白了。在那种情况下,我很惊讶您尝试了您所做的代码,据我所知,C++ never 允许隐式向下转换。我错过了什么吗?
-
From cppreference: "
atomic_ref对象引用的对象的子对象不能同时被任何其他atomic_ref对象引用。"这意味着有一个atomic_ref引用派生类的一个对象和另一个引用其基类子对象的行为将是未定义的行为,正如您设想的强制转换所需要的那样。 -
您尝试做的事情对我来说没有任何意义。听起来像XY problem。你为什么要通过
atomic_ref持有components- 是否以某种方式同时访问它们?您在哪里以及如何存储这些引用所引用的实际Component对象?显示minimal reproducible example。
标签: c++ multithreading casting stdatomic