【问题标题】:Getting the type specifier given an object获取给定对象的类型说明符
【发布时间】:2011-06-26 19:48:19
【问题描述】:

我正在尝试编写一个模板函数,该函数将采用 STL 容器并显示其中元素的所有出现以及它们出现的数量。我打算使用地图,遍历容器并添加一个新元素(如果它不存在)或增加该元素的出现次数。

声明:

template < typename Container_t >
void findOccurrences (const Container_t& inContainer);

我的问题是:我能以某种方式获得容器所包含元素的类型说明符吗? 因此,当我创建地图时,键值将是inContainer 中的元素。 类似的东西:

map < typeid ( * inContainer.begin()), int > occurrences;

或者我是否必须将我的模板更改为这样的:

template < typename Container_t , typename Element_t >
void findOccurrences ( const Container_t & inContainer , Element_t dummy )
{
  map < Element_t , int > occurrences;
}

谢谢

【问题讨论】:

    标签: c++ templates stl types


    【解决方案1】:

    这样的事情怎么样:

    #include <map>
    #include <iterator>
    
    template <typename Iter>
    void histogram(Iter begin, Iter end)
    {
      typedef typename std::iterator_traits<Iter>::value_type T;
    
      std::map<T, size_t> h;
    
      while (begin != end) ++h[*begin++];
    
      // now h holds the count of each distinct element
    }
    

    用法:

    std::vector<std::string> v = get_strings();
    histogram(v.begin(), v.end());
    

    【讨论】:

    • iterator_traits 也需要 C++0x,不是吗?
    • @Ben: Err... 不,iterator_traits 对 C++0x 来说并不陌生
    • @Ben:不,iterator_traits 一直都在
    • @Space_C0wb0y:通用性好!不过,我应该说const Iter end 吗? @Ben:没有iterator traits,你不能使用迭代器!
    【解决方案2】:

    你想要typename Container_t::element_type

    也就是说,

    std::map <typename Container_t::element_type, int>
    

    【讨论】:

    • 保留以_t 结尾的名称。
    • @Ben:我不知道这在任何范围内是否完全正确......但这与这个问题无关。无论如何感谢您的信息:)
    • @Ben:我从未在标准中看到任何关于保留这些名称的内容。
    • @Ben:这是关于全局范围的,不是吗?在这种情况下,这根本不是问题
    【解决方案3】:

    使用 C++0x,真的很简单:

    map<decltype(*c.begin()), int> occurrences;
    

    对于 C++03,您可能需要使用容器中的 typedef:

    template<typename Container>
    // ...
    map<Container::element_type, int> occurrences;
    

    【讨论】:

    • 这是decltype,而不是declspec
    • @DeadMG:没错!谢谢。
    【解决方案4】:

    请查看“RTTI”(运行时类型信息)

    http://en.wikipedia.org/wiki/Run-time_type_information

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-21
      • 2015-02-27
      • 1970-01-01
      • 2019-09-03
      • 2014-12-21
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      相关资源
      最近更新 更多