数字特征零和一
NumericTraits Zero and One
可以使用 itk::NumericTraits
获得某种类型的 0 和 1。因此我们可以在野外看到这种代码:
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?一定有我没有看到的优势。
在泛型编程的上下文中,特征通常是 used/useful。它在 STL 中被大量使用。
让我们考虑一下您的 NumericTraits
如下所示:
template <typename PixelT>
struct NumericTraits {
static const int ZERO = 0;
static const int ONE = 1;
};
除此之外,您也应该或可以将模板实例限制为特定类型......使用 enable_if 等
现在,出现了一种特殊的像素类型,您如何定义它的 ZERO
和 ONE
?只需专注于您的 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
检查,并且 可能 提高性能 :)
可以使用 itk::NumericTraits
获得某种类型的 0 和 1。因此我们可以在野外看到这种代码:
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?一定有我没有看到的优势。
在泛型编程的上下文中,特征通常是 used/useful。它在 STL 中被大量使用。
让我们考虑一下您的 NumericTraits
如下所示:
template <typename PixelT>
struct NumericTraits {
static const int ZERO = 0;
static const int ONE = 1;
};
除此之外,您也应该或可以将模板实例限制为特定类型......使用 enable_if 等
现在,出现了一种特殊的像素类型,您如何定义它的 ZERO
和 ONE
?只需专注于您的 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
检查,并且 可能 提高性能 :)