2012-08-12 68 views
1

我有一個模板類,我想在vector中添加此類的實例,然後遍歷該vector無法創建模板向量迭代器

用下面的代碼:

template <typename T> 
class a { }; 

template <typename T> 
void test(vector< a<T> >) { 
    vector< a<T> >::iterator it; 
} 

我得到的錯誤:

In function ‘void test(std::vector<a<T>, std::allocator<a<T> > >)’: 
error: expected `;' before ‘it’ 

我在做什麼錯?

回答

1

你需要

typename vector< a<T> >::iterator it; 

因爲iterator是這方面的一個從屬名稱。這意味着編譯器無法知道something<template parameter>::iterator是一種類型還是別的。明確添加typeneme關鍵字可以解決該問題。

1
template <typename T> 
void test(vector< a<T> >) { 
    vector< a<T> >::iterator it; 
} 

迭代器是dependent-name。使用typename vector<a<T> >::iterator it;

n3337 14.6/2

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.