2012-12-26 167 views
2

所以我有我的模板类的一些问题。C++类嵌套到模板类

<!-- language: lang-c++ --> 

template<class T> 
class List { 
    class Counter 
    {  
    T real; 
    T imaginary; 
    Counter *next; 
//.... 
    public: 
    Counter(T a=0,T b=0);     
    virtual ~Counter();      
    friend ostream& operator<<(ostream&,Counter&); 
    friend ostream& operator<<(ostream&,List&); 
    }; 
    Counter* first; 
    Counter* last; 
//.... 
}; 

但我有一些方法的问题。如果我写的功能

template<class T> Counter operator/(Counter &one,...) 

当我在VC++ 10看柜台它说,像

<error_type>&one 

例如。我应该在代码中的任何地方使用template<class T>作为我的Counter类吗?

//Methods 
//Counter. For example some methods 
Counter operator/(Counter& one,Counter& two){} 
ostream& operator<<(ostream&os,Counter&x){} 
istream& operator>>(istream&is,Counter&x){} 
//List 
template<class T>void List<T>::add(Counter *T,int i,bool c){} 
+0

是的,你应该。除非您定义函数内联,否则您需要为每个方法定义提供模板参数。 – atoMerz

+0

据我所知,是的,如果你需要在计数器中使用模板类。 – swtdrgn

回答

2

这取决于你是否定义了运营商(无论他们是否是成员函数或全球运营商)类定义或之外的它

如果你这样做的类定义中,没有必要为template<T>,也不是为List<T>

template <typename T> 
class List 
{ 
public: 
    class Counter 
    { 
    /* This is a global operator* defined inside the class, and 
     as friend. */ 
    friend Counter operator*(const Counter &c1, const Counter &c2) 
    { 
     return Counter(); 
    } 
    }; 

}; 

(请注意,我的operator*定义实际上不是有用,因为它总是返回一个空Counter这只是为了演示语法。)

但是,如果您在类之外定义运算符(因此也在List的模板定义之外),则必须使用函数模板定义的完整语法:

template <typename T> 
typename List<T>::Counter operator/(const typename List<T>::Counter &c1, const typename List<T>::Counter &c2) 
{ 
    return List<T>::Counter(); 
} 

正如你所看到的,这包括三个步骤:

  1. template <....>,所有模板参数的定义之前封闭在< ... >名称。
  2. 使用List<T>::Counter以指示Counter是一个嵌套类型名
  3. 使用typename List<T>::Counter因为Counter嵌套成依赖型(即依赖于模板参数类型)。
+0

所以据我所知 template typename List ::计数器*列表 :: Node_find(int i) 对我的编译器没有错误吗? – Jamakase

+0

恩,是吗?这对我来说似乎是正确的,但如果仍然存在错误,请告诉我。 – jogojapan