2015-11-25 13 views
0

我有一些模板spezialized特定的數據類型。現在在x64版本中,類型是不同的,所以它工作正常。對於x32構建,數據類型是相同的,所以我想知道如果我只能在數據類型不同時才進行條件編譯。條件編譯,如果數據類型不同

template <> const usize_t NumericColumn<int_t>::MinDefault = (usize_t)INT_MIN; 
template <> const usize_t NumericColumn<int_t>::MaxDefault = (usize_t)INT_MAX; 
template <> const usize_t NumericColumn<uint_t>::MinDefault = (usize_t)0; 
template <> const usize_t NumericColumn<uint_t>::MaxDefault = (usize_t)UINT_MAX; 

// May not work in 32 bit build, but so far we don't need this anyway and if it is 
// desired, it needs to be adjusted accordingly with an ifdef WIN32/WIN64 
template <> const usize_t NumericColumn<ssize_t>::MinDefault = (usize_t)LLONG_MIN; 
template <> const usize_t NumericColumn<ssize_t>::MaxDefault = (usize_t)LLONG_MAX; 
template <> const usize_t NumericColumn<usize_t>::MinDefault = (usize_t)0; 
template <> const usize_t NumericColumn<usize_t>::MaxDefault = (usize_t)ULLONG_MAX; 

在X32 usize_tuint_tint,所以我得到一個編譯錯誤,因爲模板實例化兩次。

我可以科西嘉的使用

#ifdef WIN64 
    template usize_t... 
#endif 

但我在想,如果我能做到這一點在C++與比較類型本身,這將是清潔IMO。如果我使用static_assert,我只能產生一個錯誤,這當然不是我在這裏需要的。

回答

2

你需要的是已經在標準庫:

template <typename T> 
const usize_t NumericColumn<T>::MinDefault = std::numeric_limits<T>::min(); 
template <typename T> 
const usize_t NumericColumn<T>::MaxDefault = std::numeric_limits<T>::max(); 

至於你實際上問的問題,你可以使用編譯時程序:

template <typename T> 
const usize_t NumericColumn<T>::MinDefault = DefaultComputer<T>::min; 
template <typename T> 
const usize_t NumericColumn<T>::MaxDefault = DefaultComputer<T>::max; 

並執行DefaultComputer作爲元程序來執行所需的計算,例如通過存儲類型 - 值對的列表並採用匹配類型的第一個條目。

也許更好的方法是根據你知道的不同類型名稱進行專業化;例如假設你正在使用合適的類型,

template <typename T> 
const usize_t NumericColumn<int32_t>::MinDefault = INT32_MIN; 
template <typename T> 
const usize_t NumericColumn<uint32_t>::MinDefault = UINT32_MIN; 
template <typename T> 
const usize_t NumericColumn<int64_t>::MinDefault = INT64_MIN; 
template <typename T> 
const usize_t NumericColumn<uint64_t>::MinDefault = UINT64_MIN; 
+0

我試過使用'std :: numeric_limits :: min()'的方法,但由於某些原因,它不適用於VS 2010(即使我認爲它是正確的方法)。它與Windows最小/最大宏(IMO是一個編譯器錯誤)混淆,但即使當我刪除它,仍然有編譯器錯誤引用函數,所以我認爲VS2010還沒有它。我最終基本上使用了你在底部提到的方法,所以我不需要ifdefs。 – Devolus

+0

@Devolus嘗試'(std :: numeric_limits :: min)()'。注意額外的parens。 VS2010肯定有'std :: numeric_limits '。 – Simple

1

我認爲你正在尋找這樣的:

enable_if<is_same<uint_t, usize_t>::value> 
+2

你如何在OP的例子中使用它? – Jarod42