2017-10-06 41 views
0

我有一個模板類,我嘗試通過運算符重載爲模板verision轉換爲另一種C++與運算符重載轉換模板

enum MyTypes {A,B,C} 

template<MyTypes T> 
MyClass { 
    const static MyType type_ = T; 
    template<MyTypes U>  
    MyClass<U> convert(MyTypes t) { 
     MyType<U> ret = MyType<U>(); 
     .... 
     return r; 
    } 
    template<MyTypes U>  
    MyClass<U> operator()() { 
     return convert(U); 
    } 
} 

然而,這種收益率(海合會,C11)

conversion from MyClass<0u> to non-scalar type MyClass<1u> requested 

除去模板功能,並試圖

MyClass<A> operator()() { 
    MyClass<A> a = MyClass<A>(); 
    ... 
    return a; 
} 

拋出

the error operator cannot be overloaded 

基本上,我想實現的是,如果我有

MyClass<A> a = MyClass<A>; 
MyClass<B> b = a; 

它創建基於一個和轉換一個新的MyClass的。任何想法這裏我的錯誤是什麼?

編輯: 我拋出了一個模板功能,只需留下操作

template<MyTypes U>  
MyClass<U> operator()() { 
    MyClass<U> ret = MyClass<U>(); 
    ... 
    return ret; 
} 

而是試圖做

MyClass<B> = a 
+0

'轉換(U)'。這裏的模板參數是什麼?不,這不是'U'。想想看。 –

+1

什麼是MyType?什麼是'r'?你可以發佈[mcve]我們可以複製和粘貼並獲得完全相同的錯誤信息嗎? – aschepler

+0

對不起,但是......用'MyType ret = MyType ();'(在'convert()'內部),你的意思是'MyClass r = MyClass ();'? – max66

回答

1

下轉換時,這仍然產生

conversion from MyClass<0u> to non-scalar type MyClass<1u> requested 

該值並允許分配:

#include <iostream> 
#include <string> 

enum MyTypes { A, B, C }; 

template<MyTypes T> 
struct MyClass{ 
    const static MyTypes type_ = T; 
    std::string history{"started as " + std::to_string(T)}; 

    template<MyTypes U> 
    operator MyClass<U>() { 
     return {history+" then became " + std::to_string(U)}; 
    } 
}; 

int main() 
{ 
    MyClass<A> a; 
    MyClass<B> b = a; 
    MyClass<C> c = b; 

    std::cout << a.history << '\n'; 
    std::cout << b.history << '\n'; 
    std::cout << c.history << '\n'; 
} 

輸出:

started as 0 
started as 0 then became 1 
started as 0 then became 1 then became 2 
+0

謝謝,修復它。看起來像其他小項目中的我的基本錯誤是意外地超載了錯誤的操作符 – chrise