我正在尝试使用std :: map和Type类在C ++中创建一个类型映射,它存储类型。然后有一个基类Base和一些我想要存储的Derived类。
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();
但是当尝试做这样的事情时,我得到了错误:类型&#34的类型;类型&lt;导出&GT; *&#34;无法分配到类型&#34;类型&lt;的实体。基&GT; *&#34;
map<int, Type<Base>*> typeMap;
typeMap[1] = new Type<Derive>();
有没有机会存储这样的东西?我不想要任何图书馆解决方案(非开源)
答案 0 :(得分:2)
与@ 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");
答案 1 :(得分:1)
对要映射的每种类型的整数专门化struct
。
#include <cstddef> // size_t
struct Base {};
struct Derived : Base {};
template<std::size_t i>
struct my_map;
// specialize the map (maybe shorten with a macro)
template<>
struct my_map<0> {
using type = Base;
};
template<>
struct my_map<1> {
using type = Derived;
};
// easier to use, if you compiler supports it:
template<std::size_t i>
using my_map_t = typename my_map<i>::type;
int main()
{
my_map<0>::type* b1 = new Base();
my_map<0>::type* b2 = new Derived();
my_map<1>::type* d1 = new Derived();
// my_map<1>::type* d2 = new Base(); error wrong type
// prettier
my_map_t<0>* b3 = new Base();
return 0;
}