2014-11-20 117 views
0

我想寫一個幫助器結構來測試類的靜態條件。如果條件爲真,則應該在堆中分配一個對象,並且指向該對象的指針應該返回到std :: vector。C++ variadic模板委託循環錯誤

這些對象的樣子:

class BASE { 
    public: 
     virtual void func() = 0; 
}; 

class A : public BASE { 
    public: 
     const static int I = 0; 

     void func() { 
     std::cout << "CLASS A" << endl; 
     } 
}; 

class B : public BASE { 
    public: 
     const static int I = 1; 

     void func() { 
     std::cout << "CLASS B" << endl; 
     } 
}; 

限位結構:

template<class... R> 
struct cond {}; 

template<class T, class... R> 
struct cond<T, R...> : cond<R...> { 
    cond(vector<BASE *> &_b) : cond(_b) { 
     if(T::I == 1) 
     _b.emplace_back(new T()); 
    } 
}; 

,並在主函數的地方:

std::vector<BASE *> b; 
cond<A, B> t(b); 
for(auto *x : b) { 
    x->func(); 
} 

理論上在COND結構的構造應調用它的父類的構造函數,但C++ 11還引入了一個特性來在constru中調用構造函數ctors(代表團)。因此,編譯器接縫認爲我想調用構造函數在同一個班級,造成此錯誤:

./main.cpp:83:34: error: constructor for 'cond' creates a delegation cycle [-Wdelegating-ctor-cycles] 

簡單的移動矢量到全球範圍,刪除構造函數參數的作品,但我會prefere的其他解。

是否有可能告訴編譯器以某種方式解釋cond(_b)的權利?

回答

0

就讓它類的一部分,你使用它,明確給予完整類型:

template<class... R> 
struct cond {}; 

template<class T, class... R> 
struct cond<T, R...> : cond<R...> { 
    cond(vector<BASE *> &_b) : cond<R...>(_b) { 
     if(T::I == 1) 
     _b.emplace_back(new T()); 
    } 
}; 

在構造函數中的:後充分類型,正是因爲它在的繼承列表提供類 - cond<R...>

編輯: 至於錯誤,沒有找到構造函數,請注意它是真的。這個類:

template<class... R> 
struct cond {}; 

不具備的,所以你應該添加這樣的事情,它應該工作:

template<class... R> 
struct cond 
{ 
    template<typename...T> 
    cond(T...) 
    { 

    } 
}; 
+0

這導致了這個錯誤:'./main.cpp:83:34 :錯誤:沒有匹配的構造函數用於初始化'cond <>''(使用Clang,但不能用於GCC) – Mense 2014-11-20 21:03:08

+0

@Mense - 這是正確的,因爲「tail」類沒有構造函數。你需要添加一個。我用這些信息編輯了答案。 – 2014-11-20 21:11:26

+0

謝謝;現在工作。 – Mense 2014-11-20 21:16:06