【发布时间】:2023-03-18 19:24:01
【问题描述】:
我有这个问题(直方图)。我有一个真实的空间:[a,b] 以某种方式分区 ([a0=a, a1, a2, ..., b])。分区可以是相等的空间 (a1 - a0 = a2 - a1 = ...) 或变量。
我需要一个类来处理这个问题,并通过一些方法说给定它所属分区的 bin 的值;查找特定 bin 中心的其他方法等等。
在程序中我不喜欢实例化一个类只调用这些简单的函数像
Binner binner(binning);
binner.get_bin(1.3);
binner.get_centerbin(2);
所以我尝试使用模板编写一个静态类来做类似的事情:
Binner<binning>::get_bin(1.3);
Binner<binning>::get_centerbin(2);
这是个好主意吗?还有其他方法吗?现在我有免费的功能,比如
double get_bin(double bin, Binning binning); // a lot of if/else inside
但我认为这太容易出错了。
这是我的实现:
enum Binning {CELL, LARGE, BE};
const double binning_LARGE[] = {0, 1.2, 1.425, 1.550, 1.800, 2.5};
const double binning_BE[] = {0, 1.425, 1.550, 2.5};
template<Binning binning>
class Binner
{
public:
static const double* bins;
static const int n;
static int get_bin(double value);
};
template<> const double* myclass<LARGE>::bins = binning_LARGE;
template<> const double* myclass<BE>::bins = binning_BE;
template<> const int myclass<LARGE>::n = sizeof(binning_LARGE) / sizeof(double);
template<> const int myclass<BE>::n = sizeof(binning_BE) / sizeof(double);
template<Binning binning> int myclass<binning>::get_bin(double value)
{
return find_if(bins, bins + n,
bind2nd(greater<double>(), value)) - bins - 1;
}
template<> int myclass<CELL>::get_bin(double value)
{
return static_cast<int>(value / 0.025);
}
- 这是一个好的实现/设计吗?
- 有没有办法避免使用
n字段使用std::vector?怎么样? -
有没有办法对
0.025进行参数化?我知道double不能是模板参数,但我可以写类似这样的东西吗:Binner<0.025> binner; - 其他/建议?
编辑:
第三点为什么我不能这样做:
template<Binning binning, int N=100>
class Binner
{
public:
static const double* bins;
static const int n;
static int bin(double value);
};
...
template<Binning binning, int N> int Binner<CELL, N>::bin(double value)
{
return static_cast<int>(value / (2.5 / N));
}
【问题讨论】:
-
+1,不知道
double不能是template参数。 -
看起来很好地展示了模板的使用。但我感觉你所做的一切都可以通过选择合适的 STL 容器并定义所需的方法来实现。
标签: c++ templates static histogram static-polymorphism