2012-04-04 152 views
1

寫模板函數的形式(如果有的話)是什麼,其中參數是模板化的容器?帶模板參數的模板函數的類型推斷

例如我想寫一個通用的總和,它可以在任何可以迭代的容器上工作。鑑於下面的代碼,我必須寫例如sum<int>(myInts)。我寧願寫sum(myInts)以及從myInts包含的類型推斷出的類型。

/** 
@brief Summation for iterable containers of numerical type 
@tparam cN       Numerical type (that can be summed) 
@param[in] container    container containing the values, e.g. a vector of doubles 
@param[out] total     The sum (i.e. total) 
*/ 
template<typename N, typename cN> 
N sum(cN container) { 
    N total; 
    for (N& value : container) { 
     total += value; 
    } 
    return total; 
} 
+2

你知道有'std :: accumulate' for那? – jrok 2012-04-04 16:47:20

回答

0

此,即使麻煩,可以做C++ 11的伎倆:

template <typename C> 
auto sum(C const & container) 
    -> std::decay<decltype(*std::begin(container))>::type 

另一種選擇是隻用積聚做同樣的結構:有呼叫者傳遞一個額外的參數與初始值並使用它來控制表達式的結果:

template<typename N, typename cN> 
N sum(cN container, N initial_value = N()) 

(通過提供默認值,用戶可以決定調用它的值或提供模板參數 - 但這需要類型N默認可構造)

+0

這是什麼箭頭?它是否與lambda表示法中使用的箭頭相同? – zenna 2012-04-04 17:11:31

+1

@zenna:這是提供結尾返回類型的語法,是的,它的作用與lambda中相同:'[](int x) - > double {return 3 * x; }' – 2012-04-04 17:27:03

+0

由於某種原因,它的decltype(* std :: begin(container))是一個引用(我認爲是int)。 – zenna 2012-04-04 17:49:50

3

我寫這樣的函數像這樣

template<typename IT1> 
typename std::iterator_traits<IT1>::value_type //or decltype! 
function(IT1 first, const IT1 last) 
{ 
    while(first != last) 
    { 
     //your stuff here auto and decltype is your friend. 
     ++first; 
    } 
    return //whatever 
} 

這樣,它就會多隻集裝箱進行更多的合作,比如ostream的迭代器和目錄迭代器。

呼叫像

function(std::begin(container), std::end(container)); 
相關問題