我試圖寫一個模板函數,它接受一個任意容器類具有任意數值類型元素類型:獲取從模板容器類型
template <typename NumType, typename ContType>
double avg_nums(const ContType<NumType> & data)
{
double sum = 0;
for(ContType::const_iterator iter = data.cbegin(); iter != data.cend(); ++iter)
{
if(typeid(NumType) == typeid(char) || typeid(NumType) == typeid(unsigned char))
{
std::cout << static_cast<int>(*iter) << std::endl;
}
else
{
std::cout << *iter << " ";
}
sum += *iter;
}
std::cout << std::endl;
return sum/data.size();
}
但是這給了語法錯誤(VS2012)。這不起作用或者:
template <typename NumType, typename ContType<NumType> >
double avg_nums(ContType<NumType> & data)
我想要的對象類型的容器是一個模板參數,以及容器類型,所以我可以爲NumType的特定情況下增加檢查。如果我改變函數簽名
template <typename NumType, typename ContType>
double avg_nums(ContType & data)
它建立,但現在它依賴於明確地指定了正確的模板參數:
std::vector<char> cvec = boost::assign::list_of(0) (1) (1) (2) (3) (5);
std::vector<int> ivec = boost::assign::list_of(0) (1) (1) (2) (3) (5);
avg_nums<char, std::vector<char>>(cvec);
avg_nums<int, std::vector<int>>(ivec);
如果我改變了簽名
template <typename ContType>
double avg_nums(ContType & data)
它的工作原理但現在我沒有直接訪問元素類型。我可以從容器的類型中獲取元素類型(std::vector<int>
或std::list<unsigned char>
)嗎?