首页 > 解决方案 > 在不知道模板参数的映射中获取派生类的模板参数类型

问题描述

我正在尝试在这种情况下获取模板参数类型:

#include <iostream>
#include <string>
#include <map>
#include <typeinfo>

class Base {
public:
    typedef char myType;
};

template <typename T>
class Derived : public Base {
public:
    typedef T myType;
};

int main() {
    std::map<std::string, Base*> myMap;
    myMap["test1"] = new Derived<int>();
    myMap["test2"] = new Derived<float>();

    std::cout << typeid(myMap["test1"]).name() << std::endl; // prints Base
    std::cout << typeid(myMap["test2"]).name() << std::endl; // prints Base

    //myMap["test1"]->myType test; // invalid use of 'Base::myType'

    std::cout << typeid(dynamic_cast<Derived*>(myMap["test1"])->myType).name() << std::endl; // invalid use of template-name 'Derived' without an argument list. Should print "int" ...
    std::cout << typeid(dynamic_cast<Derived*>(myMap["test2"])->myType).name() << std::endl; // invalid use of template-name 'Derived' without an argument list. Should print "float" ...
}

该映射包含 Base 类型的元素,因此也包含带有模板参数的 Derived 类型的元素。但是,在从地图中检索元素时,我无法再次获取模板参数类型。我试图向这两个类添加一个 typedef,但它不起作用。

你有解决这个问题的提示吗?

提前致谢!

标签: c++templates

解决方案


你有解决这个问题的提示吗?

类型名称不像virtual成员函数那样工作。你需要的是一个virtual成员函数。

这是一个演示程序:

#include <iostream>
#include <string>
#include <map>
#include <typeinfo>

class Base {
public:
    virtual std::type_info const& myType() const { return typeid(char); }
};

template <typename T>
class Derived : public Base {
public:
    virtual std::type_info const& myType() const { return typeid(T); }
};

int main() {
    std::map<std::string, Base*> myMap;
    myMap["test1"] = new Derived<int>();
    myMap["test2"] = new Derived<float>();

    std::cout << myMap["test1"]->myType().name() << std::endl;
    std::cout << myMap["test2"]->myType().name() << std::endl;
}

使用 g++ 输出:

i
f

推荐阅读