我有一个带有未知键和值类型的映射,我想在不事先知道键类型的情况下确定值类型的typeid(...).name():
std::map<K, V> aMap;
// This gives me the typeid(...).name(), but requires knowing the key type
typeid(aMap[0]).name();有没有办法在不知道V是什么类型的情况下获得K的typeid(...).name()?
应该注意的是,我仅限于使用C++03;但是,如果有办法在C++11或更高版本中实现这一点,那将是很酷的。
发布于 2018-09-12 07:39:38
假设您至少知道您正在处理的是一个std::map,那么您可以使用模板函数或多或少地直接获取键和值类型:
#include <iostream>
#include <string>
#include <map>
template <class T, class U>
std::string value_type(std::map<T, U> const &m) {
return typeid(U).name();
}
int main() {
std::map<int, std::string> m;
std::cout << value_type(m);
}为std::string输出的实际字符串是实现定义的,但至少这为您提供了某种旨在表示该类型的内容,而不是将其硬编码到value_type或类似的内容中。
在std::map的特定情况下,您可以改用mapped_type --上面的模板方法也适用于没有定义任何类似内容的模板。
https://stackoverflow.com/questions/52285425
复制相似问题