2011-12-11 4 views
32

可能性の重複:それはある.TEMPLATE(ドット・テンプレート)建設の使用

#include <iostream> 

template <int N> 
struct Collection { 
    int data[N]; 

    Collection() { 
    for(int i = 0; i < N; ++i) { 
     data[i] = 0; 
    } 
    }; 

    void SetValue(int v) { 
    for(int i = 0; i < N; ++i) { 
     data[i] = v; 
    } 
    }; 

    template <int I> 
    int GetValue(void) const { 
    return data[I]; 
    }; 
}; 

template <int N, int I> 
void printElement(Collection<N> const & c) { 
    std::cout << c.template GetValue<I>() << std::endl; /// doesn't compile without ".template" 
} 

int main() { 
    Collection<10> myc; 
    myc.SetValue(5); 
    printElement<10, 2>(myc); 
    return 0; 
} 


Where and why do I have to put the “template” and “typename” keywords?

私は、コードの奇妙なセグメントに遭遇しました。テンプレートのキーワードなしでコンパイルされませんprintElement関数。私は以前これを見たことがないし、何が必要なのか分からない。それを削除しようとすると、テンプレート関連のコンパイルエラーが多発しています。だから私の質問は、そのような工事が使われる時でしょうか?それは一般的ですか?

+8

:より詳細な説明については

は、ここでは受け入れ答えを読みますトークン、ドット、 'template'キーワードが続きます。 'cと書くことも合法です。テンプレートGetValue '。 'template'は、ドットではなくメンバ関数' GetValue'に結び付けられます。 – jalf

答えて

40

GetValueは依存名で、あなたが明示的に何cを次のことは機能テンプレート、ではないいくつかのメンバデータであることをコンパイラに指示する必要があります。そのため、これを明確にするために、templateというキーワードを記述する必要があります。

templateキーワードがなければ、以下

c.GetValue<I>() //without template keyword 

として解釈することができる:、<が少ないよりオペレータとして解釈され、>が大なりとして解釈される

//GetValue is interpreted as member data, comparing it with I, using < operator 
((c.GetValue) < I) >() //attempting to make it a boolean expression 

オペレーター。上記の解釈はもちろん間違っています。なぜなら、それは意味をなさないので、コンパイルエラーにつながるからです。それは `.template`(単一ドット・テンプレートの構造)が、二つではありません、念のため

関連する問題