[英]Default template parameter in constructor
因此,我有這段代碼,為了方便起見,我希望其構造函數的默認參數為int類型,且為0。(我的項目類中有更多參數,其中一個是可選參數,我不想要寫兩次構造函數,因為它很大
class mama{
public:
template<typename x> mama(x i=int(0)){}
};
int main(){
mama x;
}
這是行不通的,因為它說找不到構造函數,所以還有另一種方法可以做到這一點嗎?
error: no matching function for call to ‘mama::mama()'
note: candidates are: mama::mama(const mama&)
將構造函數重構為私有的初始化函數和包裝構造函數,然后添加一個默認值,如下所示:
class mama {
private:
template<typename x> void init(x i) { /* ... */ }
public:
template<typename x> mama(x i) { init(i); }
mama() { init((int)0); }
};
請注意,功能模板不允許使用默認模板參數。 為什么不創建類模板?
template <class T=int>
class mama{
public:
mama<T>(T i=0){}
};
int main(){
mama<> x; // no argument based template parameter deduction possible
}
默認值就像過載一樣工作,所以...
class mama{
public:
template<typename x> mama(x i){}
mama(int i = 0) {}
};
當您創建不帶參數的媽媽時,具有默認int的構造將在任何模板構造函數之前匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.