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

bas*_*sil 2 c++ reflection dictionary stdmap c++03

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

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

有没有办法在不知道什么类型的情况下获得typeid(...).name()for ?VK

应该指出的是,我仅限于C++ 03; 但是,如果有可能在C++ 11或更高版本中执行此操作,那么知道它会很酷.

Jer*_*fin 7

假设您至少知道您正在处理的是一个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);
}
Run Code Online (Sandbox Code Playgroud)

打印出来的实际字符串std::string是实现定义的,但至少这会为您提供一些旨在表示该类型的内容,而不会将其硬编码value_type或类似内容.

在特定情况下std::map,您可以使用mapped_type- 上面的模板方法也适用于那些没有定义类似内容的模板.