2010-12-04 74 views
4

下面是幾個相關但不同的類。一個包含一個浮動列表;一個只包含一個。有時候我想說,把它們放在一起。在這種情況下,我想'推廣'非列表到列表。這是代碼,它以我想要的方式工作。當我進行模板化時,隱式轉換不會發生

#define LIST_SZ 4 

class Vec1; 

class Vec1_list { 

    public: 
     Vec1_list() {} 
     Vec1_list(const Vec1& in); 

     float x[LIST_SZ]; 
}; 

class Vec1 { 

    public: 
     Vec1() {} 
     Vec1(const float& in); 

     float x; 
}; 

Vec1::Vec1(const float& in) { 
    x = in; 
} 

Vec1_list::Vec1_list(const Vec1& in) { 
    for (int i = 0; i < LIST_SZ; i++) { 
     x[i] = in.x; 
    } 
} 

Vec1_list operator*(const Vec1_list& a, const Vec1_list& b) { 
    Vec1_list tmp; 

    for (int i = 0; i < LIST_SZ; i++) { 
     tmp.x[i] = a.x[i]*b.x[i]; 
    } 

    return tmp; 
} 

int main(void) { 
    Vec1 v1; 
    Vec1_list v2, v3, answer; 

    answer = v1*v3; 
} 

但現在說我要模板化它像這樣....

#define LIST_SZ 4 

template <typename T> class Vec1; 

template <typename T> 
class Vec1_list { 

    public: 
     Vec1_list() {} 
     Vec1_list(const Vec1<T>& in); 

     T x[LIST_SZ]; 
}; 

template <typename T> 
class Vec1 { 

    public: 
     Vec1() {} 
     Vec1(const T& in); 

     T x; 
}; 

template <typename T> 
Vec1<T>::Vec1(const T& in) { 
    x = in; 
} 

template <typename T> 
Vec1_list<T>::Vec1_list(const Vec1<T>& in) { 
    for (int i = 0; i < LIST_SZ; i++) { 
     x[i] = in.x; 
    } 
} 

template <typename T> 
Vec1_list<T> operator*(const Vec1_list<T>& a, const Vec1_list<T>& b) { 
    Vec1_list<T> tmp; 

    for (int i = 0; i < LIST_SZ; i++) { 
     tmp.x[i] = a.x[i]*b.x[i]; 
    } 

    return tmp; 
} 

int main(void) { 
    Vec1<float> v1; 
    Vec1_list<float> v2, v3, answer; 

    answer = v1*v3; 
} 

的「MULT」使編譯器嗆這個時候 - 它不會自動調用我的VEC 1 - > Vec1_list構造函數。這是C++生活的一個事實,還是有一些方法可以用來自動實現這一點?另一種選擇是我需要有一個超級功能的粉絲。

回答

1

您必須將operator*聲明爲Vec1_list類的一個朋友,以便在實例化Vec1_list後將實例化該類,然後執行轉換。

編輯: 要做到這一點,移動運營商*定義爲Vec1_list類模板聲明:

friend static Vec1_list operator*(const Vec1_list& a, const Vec1_list& b){ 
    /* ... */ 
} 
0

我不知道爲什麼它不會促銷到所需的Vec1_list。但如果這是不可能的,那麼總是可以做到這一點:

template <typename T> 
Vec1_list<T> operator*(const Vec1<T>& a, const Vec1_list<T>& b) { 

    return Vec1_list<T>(a)*b;; 
} 

順便說一句,我仍然在挖最初的問題。

1

通過轉換構造函數進行的用戶定義轉換不被模板參數推導考慮。

模板推演試圖找到使參數化類型與參數類型相同的的函數模板參數替代。當它不能時,它是允許的(我在這裏簡化):const/volatile限定修飾或'派生到基礎'的指針轉換。

這在標準[temp.deduct.call]的14.8.2.1/3節中描述。

相關問題