我正在尝试使用 std::map 和存储类型的 Type 类在 C++ 中创建类型映射。然后有一个基类 Base 和一些我要存储的派生类。
template <typename T>
class Type {
public:
Type() {}
virtual ~Type() {}
virtual T* allocate() const { return new T; }
virtual T* cast(void *object) const { return static_cast<T*>(object); }
};
这很好用:
map<int, Base*> typeMap;
typeMap[1] = new Derive();
但是当尝试做这样的事情时,我得到了错误:类型“Type
map<int, Type<Base>*> typeMap;
typeMap[1] = new Type<Derive>();
有机会存储这样的东西吗?我不想要任何库解决方案(非开源)
最佳答案
类似于@pmr 的回答,但使用 std::tuple
#include <tuple>
#include <type_traits>
class Base{};
class Derived : public Base {};
template<std::size_t i>
struct my_map
{
private:
using myTuple = std::tuple<Base, Derived>;
public:
using type = typename std::tuple_element<i, myTuple>::type;
};
static_assert(std::is_same<Base, my_map<0>::type>::value, "bad type");
static_assert(std::is_same<Derived, my_map<1>::type>::value, "bad type");
关于c++ - 在模板中使用派生类并将其存储到基类的 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24799614/