2013-04-18 34 views
2

在C++中編寫代碼時,我想表達一個概念,即對於X類型的組件,其最小值爲kMinValue,其最大值爲kMaxValue。爲此,我做了類似的:定義浮點值特性

template <typename ComponentType> 
struct CompTraits 
{ 

}; 

template <> 
struct CompTraits<unsigned char> 
{ 
    typedef unsigned char ComponentType; 
    enum{ 
     kMinValue = 0, 
     kMaxValue = 255 
    };    
}; 

而且,我可以參考CompTraits<unsigned char>::kMinValue。但是,我無法理解浮動數據類型的技巧。有人可以幫助爲花車定義相同的東西。

在此先感謝。

+1

你知道['std :: numeric_limits'](http://en.cppreference.com/w/cpp/types/numeric_limits)嗎?例如'std :: numeric_limits :: min()'。 –

+0

是的,但我並不是指float數據類型的限制。我有我自己的組件,它有它自己的限制,所以當組件的類型爲float時,它的限制是[0,1.0],但是當它的無符號字符限制是[0,255]等等。 – Aarkan

+0

@Aarkan請注意,您也可以爲您自己的數據類型專門設置numeric_limits,這樣可以避免爲所有已定義的數據類型實現「CompTraits」。看到我的答案的最後編輯。 – zakinster

回答

5

可以使用std::numeric_limits,而不是你的常量,但如果你想只kMinValuekMaxValue - 您可以使用這樣的事情

C++ 03

template<> 
struct CompTraits<float> 
{ 
    static const float kMinValue; 
    static const float kMaxValue; 
}; 

const float CompTraits<float>::kMinValue = std::numeric_limits<float>::min(); 
const float CompTraits<float>::kMaxValue = std::numeric_limits<float>::max(); 

C++ 11

template<> 
struct CompTraits<float> 
{ 
    static constexpr float kMinValue = std::numeric_limits<float>::min(); 
    static constexpr float kMaxValue = std::numeric_limits<float>::max(); 
}; 

你的情況下,你應該簡單地使用

template<> 
struct CompTraits<float> 
{ 
    static const float kMinValue = 0.0f; 
    static const float kMaxValue = 1.0f; 
}; 
+1

我不認爲它會編譯(即使在C++ 11)。 'min()'和'max()'是函數,所以你必須使用'constexpr'而不是'const'。 – Nawaz

+0

@Nawaz當然,你是對的......現在修好了。 – ForEveR

+0

請注意,C++ 03和C++ 11版本不相同。 – Nawaz

1

不能使用enum定義這些值,因爲一個enum只能儲存整數值,可以使用常量來代替:

template <> 
struct CompTraits<double> 
{ 
    typedef double ComponentType; 
    static const double kMinValue = 0.; 
    static const double kMinValue = 1.;   
}; 

也爲標準的數字類型,你可以看看C++ STL的std::numeric_limit

numeric_limits<unsigned char>::min()會做同樣的事情,你CompTraits<unsigned char>::kMinValue,它的每一個數字類型實現的。

另外請注意,你可以專注numeric_limit爲自己的數據類型

namespace std { 
    template<> 
    struct numeric_limits<YourType> 
    { 
     static const bool is_specialized = true; 
     /* assuming YourType has a constructor from double */ 
     static const YourType min() throw() { return 0. }; 
     static const YourType max() throw() { return 1. }; 
    }; 
} 

如果你有這種做法的疑問的合法性,請參閱:

«程序可能會增加模板專門化 爲任何標準庫模板命名空間標準。標準庫模板 的這種 專業化(完整或部分)會導致未定義的行爲,除非聲明依賴於外部鏈接的用戶定義名稱的 ,並且除非專業化 滿足原始模板的標準庫要求。» 從C++ 2003, §17.4.3.1/1

2

這是因爲你用enum爲常數。枚舉常量只能是整數。

我建議您使用static const成員變量(或static constexpr,如果您使用的是C++ 11編譯器)。