2014-01-06 47 views
1

我試圖寫一個通用模板類,但我不斷收到這個錯誤,當我嘗試實現:類模板沒有匹配函數調用T :: T()

no matching function for call to type_impl::type_impl() 

其中type_impl是我正在嘗試使用該類的類型。

這裏是我的代碼:

class BaseClass { 
protected: 
    // Some data 
public: 
    BaseClass(){ 
     // Assign to data 
    }; 
}; 

template <class T> 
class HigherClass : BaseClass { 
private: 
    T data; 
public: 
    // Compiler error is here. 
    HigherClass(){}; 
    // Other functions interacting with data 
}; 

class Bar { 
private: 
    // Some data 
public: 
    Bar(/* Some arguments*/) { 
     // Assign some arguments to data 
    }; 
}; 

// Implementation 
HigherClass<Bar> foo() { 
    HigherClass<Bar> newFoo; 

    // Do something to newFoo 

    return newFoo; 
}; 

回答

4

的問題是,既然你已經爲Bar提供了一個非默認的構造函數,編譯器不再提供默認的構造函數,這是在你的代碼需要:

HigherClass(){}; // will init data using T() 

因此提供Bar的默認構造函數。例如:

class Bar { 

public: 
    Bar() = default; // or code your own implementation 
    Bar(/* Some arguments*/) { ... } 
}; 
+0

您可能想補充爲什麼會出現這種情況。例如。 「當你嘗試創建'HigherClass '時,它有一個成員'Bar data',它需要創建一個默認的構造函數。」 – clcto

+0

@clcto謝謝,我正在這樣做。我希望現在更清楚。 – juanchopanza

+0

即使她沒有嘗試編譯它,OP的代碼也會不合格... –