[英]Get template parameter type of derived class in map that doesn't know about template parameters
I am trying to get the template parameter type in this scenario: 我正在尝试在这种情况下获取模板参数类型:
#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" ...
}
The map holds elements of type Base and thus, also of type Derived with a template parameter. 该映射包含类型为Base的元素,因此还包含使用模板参数派生的类型的元素。 However on retrieving elements from the map I am not able to get the template parameter type back again.
但是,从地图上检索元素时,我无法再次获取模板参数类型。 I tried to add a typedef to both classes but it doesn't work.
我试图将typedef添加到两个类中,但是它不起作用。
Do you have hints to resolve this problem? 您是否有解决此问题的提示?
Thanks in advance! 提前致谢!
Do you have hints to resolve this problem?
您是否有解决此问题的提示?
type names don't work like virtual
member functions. 类型名称不能像
virtual
成员函数一样工作。 What you need is a virtual
member function. 您需要的是一个
virtual
成员函数。
Here's a demonstrative program: 这是一个演示程序:
#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;
}
Output with g++: 用g ++输出:
i
f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.