在不知道键的情况下获取 std::map 中值的类型

Getting the type of a value in std::map without knowing the key

我有一个包含未知键和值类型的映射,我想在事先不知道键类型的情况下确定值类型的 typeid(...).name():

 std::map<K, V> aMap;
 // This gives me the typeid(...).name(), but requires knowing the key type
 typeid(aMap[0]).name();

有没有办法在不知道 K 是什么类型的情况下为 V 获取 typeid(...).name()

需要注意的是我仅限于C++03;但是,如果有办法在 C++11 或更高版本中执行此操作,知道会很酷。

假设您至少知道您正在处理的是 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——上面的模板方法也适用于未定义类似内容的模板。