//type description example
class TextComponent_type : public _type
{
public:
using type = TextComponent;
static constexpr uInt value = 3;
};
//...
//ECSData member functions
template<uInt id>
auto& getVector()
{
return std::visit([this] (auto&& T_type)->(auto&) {
using T = typename std::decay_t<decltype(T_type)>::type;
return _getVectorFromT<T>();
}, dataMapping[id]);
}
template<typename T>
std::vector<T>& _getVectorFromT()
{
void* voidPtr = data[decltype(T::type)::value].get();
std::vector<T>* vec = static_cast<std::vector<T>*>(voidPtr);
return *vec;
}
在上面的代码中,我有一个要用数字调用的函数,比如 getVector<3>()
,具有该成员函数的类有一个名为 dataMapping 的 std::map 成员变量,作为 Key 有一个数字,作为 Value 有一个 std::variant 持有描述类型和关联值的简单结构(//type description example class on代码顶部)
所以我正在访问这个变体以检索关联的类型并将其传递给 _getVectorFromT()
为了能够转换为正确的类型并将其返回给调用者,在本示例中,返回值将是 std::vector<TextComponent>&
但是代码根本无法编译,这里有完整的代码如果你想自己试试https://godbolt.org/z/Tq32jm
所以正如标题所说,我可以从 std::visit 返回 auto& 吗?
我需要这个,因为返回值可能是 std::vector<RectComponent>&
中的任何一个, std::vector<ConstraintComponent>&
, std::vector<TextComponent>&
等等……
最佳答案
您尝试执行此操作的方式是不可能的 - 必须在编译时推断类型。
dataMapping[id]
返回相同的类型 - 您可以将这部分变成基于 traits-like 的设计 ala。
template<int id>
struct dataMapping;
template<>
struct dataMapping<0> {
using type = int; //... or whatever
}
//and so on
关于c++ - 我可以从 std::visit 返回 auto 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59247885/