簡體   English   中英

具有隱式參數的模板,前向聲明,C ++

[英]Templates with implicit parameters, forward declaration, C++

有一個帶有隱式參數的模板類聲明:

List.h

template <typename Item, const bool attribute = true>
class List: public OList <item, attribute>
{
    public:
    List() : OList<Item, attribute> () {}
    ....
};

我嘗試在不同的頭文件中使用fllowing forward聲明:

Analysis.h

template <typename T, const bool attribute = true>
class List;

但是G ++顯示了這個錯誤:

List.h:28: error: redefinition of default argument for `bool attribute'
Analysis.h:43: error:   original definition appeared here

如果我使用沒有隱式參數的前向聲明

template <typename T, const bool attribute>
class List;

編譯器不接受這種結構

Analysis.h

void function (List <Object> *list)
{
}

並顯示以下錯誤(即不接受隱含值):

Analysis.h:55: error: wrong number of template arguments (1, should be 2)
Analysis.h:44: error: provided for `template<class T, bool destructable> struct List'
Analysis.h:55: error: ISO C++ forbids declaration of `list' with no type

更新的問題:

我從模板定義中刪除了默認參數:

List.h

template <typename Item, const bool attribute>
class List: public OList <item, attribute>
{
    public:
    List() : OList<Item, attribute> () {}
    ....
};

使用類List的第一個文件具有帶有參數屬性隱式值的前向聲明

Analysis1.h

template <typename T, const bool attribute = true>
class List;  //OK

class Analysis1
{
    void function(List <Object> *list); //OK
};

第二個類使用類使用隱式值定義WITH前向定義

Analysis2.h

template <typename T, const bool attribute = true> // Redefinition of default argument for `bool attribute'
class List; 

class Analysis2
{
    void function(List <Object> *list); //OK
};

第二個類使用隱式值使用類WITHOUT前向定義

Analysis2.h

template <typename T, const bool attribute> // OK
class List; 

class Analysis2
{
    void function(List <Object> *list); //Wrong number of template arguments (1, should be 2)
};

簡單。 從定義中刪除默認值,因為您已在前向聲明中提到過該值。

template <typename Item, const bool attribute = true> //<--- remove this 'true`
class List: public OList <item, attribute>
{
  //..
};

寫:

template <typename Item, const bool attribute>  //<--- this is correct!
class List: public OList <item, attribute>
{
  //..
};

在線演示: http//www.ideone.com/oj0jK

一種可能的解決方案是聲明另一個頭文件List_fwd.h

template <typename Item, const bool attribute>
class List;

所以在List.h和Analysis.h中都包含List_fwd.h。 所以List.h成了

#include "List_fwd.h"

template <typename Item, const bool attribute = true>
class List: public OList <item, attribute>
{
    public:
    List() : OList<Item, attribute> () {}
    ...
};

和Analysis.h

#include "List_fwd.h"

您必須確保只有第一個聲明具有參數的默認值。 這可以通過首先定義一個僅向前聲明的頭,然后從List.hAnalysis.h包含它來List.h List.h的定義中,不要包含默認值。

您可以只在一個地方定義默認參數(對於給定的翻譯)。 在類聲明中這樣做是最有用的,並且在前進時定義它是個壞主意。

轉發不需要默認參數(在某些情況下你只需要輸入它)。

如果你真的想要一個默認參數,你可以創建另一個簡單的模板類型,它與forward一起實現它。 然后通過typedef訪問結果。 你可以使用前進列表來做到這一點。

您必須在每個使用它的文件中包含List.h 聲明僅適用於非模板類型。 對於模板類型,必須包含每個編譯單元的頭文件。

暫無
暫無

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

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