2011-07-07 52 views
0

模板類和init我有一個模板類,富:C++中的構造函數

template <class A, class B> 
class Foo 
{ 
public: 
    Foo(A &aInstance); 

private: 
    Attr<Foo> _attr; 
}; 

然後我還有一個叫的Attr模板類,這是我的Foo類的屬性,這需要作爲模板參數Foo類本身。

template <class C> 
class Attr 
{ 
    class SomeType 
    { 
     SomeType(); 
     ~SomeType(); 
    }; 

    Attr(const SomeType* st); 
    ~Attr(); 

private: 
    Attr(); 
} 

我想在構造函數中初始化_attr(屬性類型爲Attr),將第一個參數從模板中轉換爲SomeType。

富構造實施:

template<class A, class B> 
Foo<A, B>::Foo(A &aInstance): 
    _attr(
     (Attr<Foo<A, B> >::SomeType *) aInstance) 
{ 

} 

這不會編譯:

錯誤:預期主表達式之前「)」令牌

該錯誤是指鑄造線在富構造器實現,就好像SomeType不被識別一樣。

我現在有一個實例,但仍然有相同的錯誤。

+0

我已經回滾了您的上次編輯,因爲它使問題(及其答案)變得荒謬。請不要這樣做。至於其他編輯:這些*也*干擾現有的答案;我沒有把它們回滾,但請將來*增加*進一步澄清,不要更改現有的代碼。 –

回答

1

0)

(Attr<Foo<A, B> >::SomeType *) A) 

在這一點上,A是類型名,即一類的名稱,因此,沒有任何你可以施放。

1)

此外,Foo<A,B>取決於AB,因此,Attr<Foo<A, B> >是一個從屬名稱,太。因此,你需要一個typename那裏,以便告訴編譯器SomeType是一種類型:

(typename Attr<Foo<A, B> >::SomeType *) somePointer) 

2)

此外,在C++中,一般喜歡C++ - 蒙上C-風格轉換。你會發現他們犯了很多錯誤。又見this tutorial :)

3)

在另一方面:你確定你需要設計的中投,還是應該Attr點整整Foo<A, B>

2
template<class A, class B> 
Foo<A, B>::Foo(): 
    _attr(
     (Attr<Foo<A, B> >::SomeType *) A) 
{ 

} 

A是一種類型,並且您試圖將它傳遞給構造函數。你需要一個實例。

+1

我相信'typename'在這裏也是必要的 –

+0

你是對的!非常感謝 – Jack

1

首先,Attr類沒有(在你的代碼片段中)使用C類型,所以你應該解釋它在哪裏使用,以及C和SomeType之間的關係是什麼。

其次,在該線

Foo<A, B>::Foo(): 
    _attr(
     (Attr<Foo<A, B> >::SomeType *) A) 

A是類型,而不是一個對象。如果_attr應該用Foo對象本身初始化,那麼你應該傳遞這個指針。

Foo<A, B>::Foo(): 
    _attr(
     (Attr<Foo<A, B> >::SomeType *) this) 

然而,這一點上,Foo對象尚未建立,所以要小心你在的Attr構造函數指針做些什麼。

0

試着改變你的構造函數:

template<class A, class B> 
Foo<A, B>::Foo(A &aInstance): 
    _attr(
     (typename Attr<Foo<A, B> >::SomeType *) &aInstance) {} 

你會的,因爲你需要一個指針,需要以採取實例對象的地址添加一個地址的操作...否則aInstance會不是指針類型,而是引用類型,它實際上與傳遞對象本身(通過引用)相同,而不是指向對象的指針。

0

這對我有用。幾個typedefs有助於使模板代碼更容易理解:

template<class C> 
class Attr 
{ 
public: 
    class SomeType 
    { 
     SomeType(); 
     ~SomeType(); 
    }; 

    typedef typename Attr<C>::SomeType ReachIntoSomeType; 

    Attr(const SomeType* st) { } 
    ~Attr() { } 

private: 
    Attr(); 
}; 

template <class A, class B> 
class Foo 
{ 
public: 
    Foo(A &aInstance) : _attr(reinterpret_cast<AttrOfFoo::ReachIntoSomeType*>(aInstance))  
    { } 

private: 
    typedef Attr<Foo> AttrOfFoo; 
    AttrOfFoo _attr; 
}; 
+0

好神!代碼完全搞砸了!第一次在SO。有人能幫我糾正嗎?謝謝! – ForeverLearning