2013-03-04 104 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