【问题标题】:Getting the type of a value in std::map without knowing the key在不知道键的情况下获取 std::map 中值的类型
【发布时间】:2018-09-11 23:27:09
【问题描述】:

我有一个未知键和值类型的映射,我想在事先不知道键类型的情况下确定值类型的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 或更高版本中执行此操作,那么知道会很酷。

【问题讨论】:

  • decltype(aMap)::mapped_type ?
  • @basil XY-问题?更好地描述您想要实现的目标,而不是如何实现目标?
  • @Justin 我正在寻找 V 的类型名称作为字符串,即 typeid(...).name(),但我不知道 K 是什么类型。
  • @basil:再次:typeid(decltype(aMap)::mapped_type).name()
  • @NeilButterworth:在我看来,这取决于你在写什么类型的东西。在调试器中依赖它(或类似的东西)似乎完全合理(但我当然同意这是仅有的少数个很好的例子之一)。

标签: c++ dictionary reflection stdmap c++03


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-23
    • 2013-02-24
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多