【发布时间】:2014-08-19 17:42:30
【问题描述】:
我正在尝试处理仅与以下某些组合兼容的图像处理操作类:
- 一组维度 [1,2,3, ...]
- 一组类型 [int, float, double, ...]
一种工作方法是定义一个通用模板类来处理默认情况(即:什么都不做),如下所示:
template <int dimension, typename dataType>
class IPOperation
{
public:
void execute()
{
std::cout << "do nothing" << std::endl;
}
};
然后我必须为所有支持的类型组合编写该类的特化,例如:
template<>
class IPOperation<2,float>
{
public:
void execute()
{
std::cout << "do something" << std::endl;
}
};
但是由于支持的维度/类型组合的数量可能会变得非常大,所以这种方法完全是矫枉过正..
受策略驱动设计的启发,最好为模板类配备特定限制,如下所示:
template <int dimension, typename dataType>
class IPOperation : public supportedDimensions<2,3,4>, public supportedTypes<int, float, double>
{
void execute()
{
std::cout << "execute()" << std::endl;
}
};
到目前为止,我的糟糕做法是这样的(看起来很糟糕,我情不自禁):
#include <iostream>
#include <vector>
template <int... supportedDimensions>
class IPDimensions
{
private:
public:
static std::vector<int> getSupportedDimensions()
{
return { supportedDimensions... };
}
static bool supportsDimension(int dim)
{
std::vector<int> dimensions = getSupportedDimensions();
return std::find(dimensions.begin(), dimensions.end(), dim) != dimensions.end();
}
};
template <int dim>
class IPOperation : public IPDimensions<2,3>
{
private:
public:
void execute(void)
{
if(IPOperation::supportsDimension(dim))
{
std::cout << dim << "d is supported -> execute" << std::endl;
}
else
{
std::cout << dim << "d is not supported -> sit down and do nothing" << std::endl;
}
}
};
int main(int argc, const char * argv[])
{
IPOperation<2>* okay = new IPOperation<2>();
IPOperation<4>* notOkay = new IPOperation<4>();
okay->execute();
notOkay->execute();
}
当试图对类型应用这样的东西时,我完全迷失了。最好有某种机制来做一些检查,就像你使用策略作为特定策略的代表一样。也许我的方法是错误的,这整个事情可以通过宏、枚举或特征和 std::enable_if 来更简单地实现,以使函数只对定义的场景可见,但是因为我花了一些时间阅读一些 c++11 主题,我真的什么都不确定了。
提前感谢你们提供任何有用的建议!
【问题讨论】:
-
这些类中是否存储了任何状态?如果是无状态的,它们应该是函数吗?如果函数,标签调度。如果不这样做,可能会在方法上进行标记分离。
标签: c++ templates c++11 variadic-templates