c++ - 在不知道模板参数的映射中获取派生类的模板参数类型
问题描述
我正在尝试在这种情况下获取模板参数类型:
#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,但它不起作用。
你有解决这个问题的提示吗?
提前致谢!
解决方案
你有解决这个问题的提示吗?
类型名称不像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
推荐阅读
- json - 响应中的 JSON
- python - Python 2.7.14:“+=1 到字典项,如果键存在否则 = 1”语法不起作用
- reactjs - React-Native fetch JSON from rest service and store it as an array in state
- c# - Does the Shapes have click event and Children in WPF
- three.js - 三个JS移动组的轴位置
- promise - Does gulp.src().pipe().dest() complete before the next line? Can I call gulp.src().pipe().dest() multiple times?
- php - 服务器拒绝授权标头并且无法在实时服务器中使用 laravel 护照进行身份验证
- javascript - How to make embedded chart responsive
- python - 无法使用扩展 AbstractBaseUser 的 Django REST Framework 自定义用户登录
- django - 模型和历史模型(相同字段),将数据从一个复制到另一个