2013-03-04 103 views
1

我想爲兩個模板重載轉換運算符。模板轉換運算符

A.H

#pragma once 

#include <B.h> 

template <typename T> class A 
{ 
operator B<T>() const; 
} 

B.h

#pragma once 

#include <A.h> 

template <typename T> class B 
{ 
operator A<T>() const; 
} 

我有錯誤

error C2833: 'operator A' is not a recognized operator or type see 
reference to class template instantiation 'B<T>' being compiled 

雖然它的工作原理,如果轉換操作符是一個模板,僅過載。

+0

你使用什麼編譯器? – 2013-03-04 18:15:56

+1

也許[這](http://stackoverflow.com/questions/14909997/why-arent-my-include-guards-preventing-recursive-inclusion-and-multiple-symbol)可以幫助('#pragma once'基本上工作作爲包括後衛) – 2013-03-04 18:21:15

回答

2

您有循環依賴問題。你需要有一個向前聲明,如:

A.H:

#pragma once 

template <class T> class B; 

template <class T> class A { 
    operator B<T>() const; 
}; 

#include "B.h" 

template <class T> 
A<T>::operator B<T>() const { 
    foo(); 
} 

B.h:

#pragma once 
#include "A.h" 

template <class T> 
class B { 
    operator A<T>() const { 
     bar(); 
    } 
}; 

我假設你使用#include "A.h"。 A.h然後包括B.h.當編譯器開始編譯B.h時,它還沒有看到A.h的聲明,因此編譯器不知道如何解釋operator A<T>() const,因爲它不知道A是一個類型。

+0

謝謝你的回答。不知何故,它只適用於'模板 A類;'在B.h和'模板 B類;'在A.h沒有任何包括。編譯器 - Visual Studio 2010 – Demion 2013-03-04 18:25:15

+0

是的。它會起作用 - 我給出的答案是,如果沒有可見的「B 」類的實現,不能編譯'A :: operator B ()'的實現。這樣,兩種實現都能夠看到每個類的完整定義。請記住,在這種模式下'B '可能有'A '類型的成員,但'A '可能*不具有'B '類型的成員(但可能有類型指針的成員或參考「B 」)。 – 2013-03-04 19:34:25