我不知道如何解決一個問題,可以用以下的結構來說明:
template <typename T, unsigned WIDTH=T::width>
結構處理程式 {
static unsigned const width = WIDTH;
};
有一個結構(在本例中稱為Handler),它把一個型別T作為模板引數。在代碼庫中,在使用這個struct的地方,使用了特殊的二進制型別,它有一個成員width(型別的位元數)。由于這個Handler應該只與該二進制型別一起作業,第二個引數WIDTH的默認值是T::width。請注意,其中還有更多的代碼,但上面的代碼應該只提供一個簡短的解釋。
現在我希望能夠在這個Handler中允許float,將WIDTH設定為32作為默認引數,這樣我就可以使用Handler<float>。除了模板引數外,Handler應該可以與float一起作業。當然,如果我直接使用Handler<float>或者甚至是Handler<float, 32>(不希望的解決方案),我得到error: 'width' is not a member of 'float'。所以我需要代碼能夠在T是float時使用常量值32,否則使用T::width。
我嘗試在WIDTH的默認引數中使用三元運算子,使用std::is_same和一個特殊的函式來根據提供的型別計算寬度。這兩種嘗試也都導致了上面的錯誤。
我還研究了模板的問題。
我還研究了模板的特殊化,但是這樣一來,我還需要對WIDTH進行特殊化,而這個特殊化需要在之后提供(即Handler<float, 32>),不是嗎?
我真的希望得到一些提示/解決方案。
uj5u.com熱心網友回復:
你可以使用一個trait helper類來解決這個問題。默認情況下,它將使用::width,但可以對其他型別進行專業化處理:
template<typename T>。
結構 width_trait
{
static unsigned const width = T::width;
};
template<>
struct width_trait<float>
{
static unsigned const width = 32;
};
template <typename T, unsigned WIDTH=width_trait< T>:width>
struct Handler {
static unsigned const width = WIDTH;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/314142.html
標籤:
上一篇:我如何繪制和寫入ppm檔案?
