1

I want to overload conversion operator for two templates.

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;
}

I got error

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

Although it works if conversion operator is overloaded only in one template.

Demion
  • 857
  • 1
  • 14
  • 27
  • What compiler do you use? – hate-engine Mar 04 '13 at 18:15
  • 1
    Maybe [this](http://stackoverflow.com/questions/14909997/why-arent-my-include-guards-preventing-recursive-inclusion-and-multiple-symbol) can help (`#pragma once` basically works as an include guard) – Andy Prowl Mar 04 '13 at 18:21

1 Answers1

2

You have a cyclic dependency problem. You need to have a forward declaration, such as:

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();
   }
};

I assume you used #include "A.h". A.h then included B.h. When the compiler started compiling B.h, it had not yet seen a declaration for A.h, and thus the compiler did not know how to interpret operator A<T>() const, as it does not know that A is a type.

Robert Mason
  • 3,949
  • 3
  • 31
  • 44
  • Thank you for answer. Somehow it just works with `template class A;` in B.h and `template class B;` in A.h without any includes. Compiler - Visual Studio 2010 – Demion Mar 04 '13 at 18:25
  • Yes. It will work - the answer I gave is for the cases where the implementation of `A::operator B()` cannot compile without a visible implementation of class `B`. This way both implementations are able to see the full definition of each class. Just keep in mind that in this pattern `B` may have a member of type `A`, but `A` may *not* have a member of type `B` (but may have a member of type pointer to or reference to `B`). – Robert Mason Mar 04 '13 at 19:34