Trending News
C++:function template的問題
大家好,我有一個function template,
它原本傳入的參數是二個iterators,但現在要在function內部使用到container的value_type
請問有沒有辨法在不更動function參數的情形下,在內部定義value_type的object呢?
簡要情況如下:
------
template <typename T> void func(T beg, T end){
//如何定義container的value_type object
}
------
謝謝
說明一下這個問題的來源好了,這是C++Primer的一個問題,它要寫function template,求某個sequence中,出現次數最多的value。參數是一對「未知型態」的iterators。
原文如下:
Write a function template that takes a pair of values that represent iterators of unknown type. Find the value that occurs most frequently in the sequence.
1 Answer
- novusLv 61 decade agoFavorite Answer
1.不要管container,STL的iterator本來就可以自外於container獨立運作。iterator之value_type可以這樣獲得
template <typename T> void func(T beg, T end){
T::value_type someVar; // if T is an iterator...
}
2.不過除了iterator這類仿指標外,我們也可能拿真指標去餵函數,導致上面的程式消化不良(想像一下int*::value_type被編譯時會如何)
因此我們可以利用一個小設施來協助
template <class Iter> // 專門應付STL 式的 iterator
struct type_trait {
typedef typename Iter::value_type value_type;
};
//專門對付 真‧指標
template <class T>
struct type_trait<T*> {
typedef T value_type;
};
template <class T>
struct type_trait<const T*> {
typedef T value_type;
};
使用法如下
template <typename T> void func(T beg, T end) {
type_trait<T>::value_type someVar;
}
3.這個方法透過一個空的struct讓編譯器推導型態,而struct本身沒有狀態與功能,編譯完後就會消失,不會造成執行負擔
此法在STL的程式碼當中大量使用