正在获取给定对象的类型说明符

Getting the type specifier given an object

本文关键字:类型 说明符 对象 获取      更新时间:2023-10-16

我正在尝试编写一个模板函数,该函数将使用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;
}

感谢

这样的东西怎么样:

#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());

您想要typename Container_t::element_type

也就是说,

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

有了C++0x,它真的很简单:

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

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

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

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

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

我希望这能有所帮助。