[英]Function template and private copy constructor
我正在嘗試實現以下比較功能模板:
template<typename T>
int compare(T x, T y)
{
if (x > y)
return 1;
else if (x < y)
return -1;
else
return 0;
}
它適用於每種經典類型,但以下類將不起作用:
class c
{
private:
c &operator=(const c&) {return *this;}
c(const c &){}
public:
bool operator==(const c&) const {return true;}
bool operator>(const c&) const {return false;}
bool operator<(const c&) const {return false;}
c(){}
};
當我嘗試比較我的類的兩個實例時,編譯器大喊他不能,因為復制ctor是私有的,因此我嘗試將引用傳遞給我的函數模板,但沒有成功。 有任何想法嗎 ?
您可以使模板采用參考:
template<typename T>
int compare(const T& x, const T& y)
這樣,不涉及任何副本。
您正在傳遞需要創建參數副本的值。 這就是為什么它需要創建副本,因此需要副本構造函數的原因。 通過引用或指針傳遞將對此有所幫助。
template<typename T>
int compare(const T& x, const T& y)
要么
template<typename T>
int compare(const T* x, const T* y)
您的模板用於按值傳遞的對象,並且類中的副本Ctor需要對象引用; 編譯器將嘗試使用默認的Ctor,由於找不到該Ctor,它會大聲呼救。
解:
either define the template so that it accepts object references (as already suggested)
or
define the copy constructor
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.