2011-06-03 59 views
5

請扔一些光對莫名其妙的一塊模板麪條:模板麪條

template <typename T, typename K> class A { 
public: 
    T t; 
    K k; 

    template <int i, int unused = 0> struct AttributeType { 
    }; 

    template <int i> AttributeType<i> getAttr(); 

}; 

template <typename T, typename K> template <int i> A<T, K>::AttributeType<i> A<T, K>::getAttr<i>() { 
    return t; 
} 

我不能拿出正確的語法定義的A::getAttr()實施。目前的代碼失敗在GETATTR定義的行編譯:

error: function template partial specialization ‘getAttr<i>’ is not allowed

我應該如何改寫函數的定義?

+0

作爲一個備註,而不是一個答案,如果你定義了一個模板的成員,而不是把它們拉到模板定義之外,那麼事情通常會簡單得多。也就是說,如果'getAttr'被定義在聲明的地方,它會簡單得多。 – 2011-06-03 21:03:06

回答

7

刪除<i>函數名的後面,返回類型前添加一個typename,這是一個從屬名稱。此外,它缺少AttributeTypetemplate,因爲這是一個模板:

template <typename T, typename K> 
template <int i> 
typename A<T, K>::template AttributeType<i> A<T, K>::getAttr() { 
    return t; 
} 

其次,它有助於讓每個模板部分自己的路線。使東西更清晰。

除此之外,該功能看起來不對,還是AttributeType有一個轉換構造函數從T

+0

哇,謝謝!你是一個真正的編譯器頭:)我只需要在'AttributeType'之前添加'template'並且它工作: – ognian 2011-06-03 20:12:15

+0

@ognian:不是'template','typename'。請參閱[本FAQ](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-template-and-typename-on-dependent-names)。 – Xeo 2011-06-03 20:14:23

+0

@Xeo:模板*和*類型名: '模板 模板 TYPENAME甲 ::模板屬性類型 :: GETATTR(){ 返回噸;}' – ognian 2011-06-03 20:15:50