【发布时间】:2012-02-08 19:39:47
【问题描述】:
这是我第一次尝试使用 GCC 4.6 测试的 C++ 中的通用直方图模板函数。但是,我想将dense_histogram() 和sparse_histogram() 合并到一个通用的通用函数模板中。问题是特定于 dense 的构造函数 H h(n, 0) 在 sparse 版本 H h 中既未定义也不相关。有没有办法以一些聪明的 C++ 常规方式或静态地通过 Boost Type.Traits (#include <boost/type_traits.hpp>) 使用条件编译来解决这个问题?
#include <algorithm>
#include <limits>
#include <algorithm>
#include <vector>
#include <unordered_map>
namespace std
{
/*!
* \em Dense Histogram of \p a.
*
* \tparam V is Value Type.
* \tparam C is Count (Bin) Type.
* \tparam H is Histogram Storage Type, typically a vector.
*
* \param[in] x is a set of the input data set
*/
template <class V, class C = size_t, class H = vector<C> >
inline
H dense_histogram(const V & x)
{
typedef typename V::value_type E; // element type
size_t n = (static_cast<C>(1)) << (8*sizeof(E)); // maximum number of possible elements for dense variant
H h(n, 0); // histogram
C bmax = 0; // bin max
for_each(begin(x), end(x), // C++11
[&h, &bmax] (const E & e) { // value element
h[e]++;
bmax = std::max(bmax, h[e]);
});
return h;
}
template <class V, class H = vector<size_t> > H make_dense_histogram(const V & x) { return dense_histogram<V, size_t, H>(x); }
/*!
* \em Sparse Histogram of \p a.
*
* \tparam V is Value Type.
* \tparam C is Count (Bin) Type.
* \tparam H is Histogram Structure Type, typically a unordered_map.
*
* \param[in] x is a set of the input data set
*/
template <class V, class C = size_t, class H = unordered_map<typename V::value_type, C> >
inline
H sparse_histogram(const V & x)
{
typedef typename V::value_type E; // element type
H h; // histogram
C bmax = 0; // bin max
for_each(begin(x), end(x), // C++11
[&h,&bmax] (const E & e) { // value element
h[e]++;
bmax = std::max(bmax, h[e]);
});
return h;
}
template <class V, class H = unordered_map<typename V::value_type, size_t> > H make_sparse_histogram(const V & x) { return sparse_histogram<V, size_t, H>(x); }
}
运行使用
【问题讨论】:
-
不能用dense map来实现sparse map吗?您所做的只是切换容器的默认模板参数。我只需要一个 create_histogram 函数,在容器上进行模板化。
标签: c++ templates generics histogram conditional-compilation