2016-06-08 80 views
1

可以使用itk::NumericTraits获得某种类型的0和1。因此,我们可以在野外看到这种代码:NumericTraits Zero and One

const PixelType ZERO = itk::NumericTraits<PixelType>::Zero; 
const PixelType ONE = itk::NumericTraits<PixelType>::One; 

这感觉很沉重,很难阅读。作为程序员,我更喜欢更实用的版本,例如:

const PixelType ZERO = 0; 
const PixelType ONE = 1; 

但是它是完全等价的吗?我认为演员是在编辑过程中完成的,所以两个版本的速度应该是相同的。如果是这样的话,为什么有人想用itk::NumericTraits得到0和1?必须有我没有看到的优势。

回答

1

在泛型编程中,特征通常用于/有用。这在STL中很常用。

让我们考虑您的NumericTraits看起来象下面这样:

template <typename PixelT> 
struct NumericTraits { 
    static const int ZERO = 0; 
    static const int ONE = 1; 
}; 

除了这个,你应该还是可以约束你的模板实例,以一种特殊的类型too..using enable_if等人。

现在,出现了一种特殊类型的像素,您将如何定义ZEROONE?只是专门化您的NumericTraits

template <> 
struct NumericTraits<SpecialPixel>{ 
    static const int ZERO = 10; 
    static const int ONE = 20; 
}; 

有想法和有用性?现在,这样做的另一个好处是转换价值类型,然后使用它的标签调度:

void func(int some_val, std::true_type) {....} 
void func(int some_val, std::false_type) {.....} 

And call it like: 

func(42, typename std::conditional<NumericTraits<PixelType>::ONE == 1, std::true_type, std::false_type>::type()); 

其中超载调用由可能在编译时决定在这里,从做if - else检查,减轻你有改善性能:)