2016-06-08 75 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檢查,減輕你有改善性能:)