簡體   English   中英

使用模板時應該何時使用關鍵字“typename”

[英]When should I use the keyword "typename" when using templates

我最近一直在做一個小項目,我無法弄清楚一些事情..

我得到了一個包含類的 .h 文件,使用了 typename 模板。 在那個班級里面有一個私人班級。

template <typename T>
class Something
{
public:
        Something();
        ~Something();

        Node* Function1(int index);
        int Index(const T& id);


private:
        class Node()
        {
                public:
                T id;

                //Imagine the rest for the Node


        };      
};

當我想定義“Something”類的函數時出現問題

這是我的工作方式(在 .inl 文件中)

template<typename T>
Node* Something::Function1(int index) //Is the return type well written?
{
        // returns the node at the specified index
}

template<typename T>
int Something::Index(const T& id) //Is the parameter type well specified?
{
        // returns the index of the node with the specified id
}

所以竊聽部分是在定義部分......我是否必須告訴編譯器返回類型(在這種情況下 Node*)使用 typename 模板(像這樣: typename Node* )? 那么參數呢? typename const Node& ?

所以基本上,我什么時候必須指定函數/參數是否使用模板?

謝謝你的時間。

對於Function1 ,您需要告訴編譯器 Node 是什么——在這種情況下,它是Something<T>的嵌套類型。 因為它依賴於T (它是一個依賴名稱),你需要告訴編譯器它是一個類型,所以你必須把它寫成typename Something<T>::Node 問題是可能存在一些T ,其中Something<T>::Node實際上不是一種類型(即,如果您部分專門化Something<T> )。

對於Index ,你所擁有的很好—— const T&只是對const T的引用,編譯器知道T是什么。

簡單規則:如果Class部分依賴於模板參數,則每次使用Class::Type語法命名類型時都需要使用typename關鍵字。 Class部分可能是模板參數,也可能是類模板中的typedef等)

編輯:關於嵌套類范圍規則也有一些混淆。 這主要與typename問題無關,因此這是一個非模板示例。

class Outer {
public:
  class Inner {
  };
  Inner* func(Inner* obj);
};

Outer::Inner* func(Inner* obj)
{
}

Inner的全稱是Outer::Inner 但是您也可以在類Outer范圍Inner任何地方使用較短的名稱Inner ,包括func所有聲明。 func的定義中,返回類型不在Outer的范圍內,因此需要全名。 但是在( ,函數參數在Outer的范圍內,所以短名稱是可以的。

將其與原始示例的模板性相結合,因為Outer的等價物是Something<T> ,所以您需要typename關鍵字來表達Something<T>::Node

template<typename T>
typename Something<T>::Node * Something::Function1(int index) //Is the return type well written?
{
        // returns the node at the specified index
}

typenameclass在模板類型參數列表中是等效的:

template <class T> class C;

是相同的

template <typename T> class C;

在引用依賴名稱時需要typename地方:

template <typename T> struct A {
    typedef typename T::some_type container;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM