nested classes and friend declaration

  • Thread starter Alexander Stippler
  • Start date
A

Alexander Stippler

Hi

what's wrong about the following code? It does not compile.

template <typename T>
class A {
public:
class B;
};

template <typename T>
bool
operator==(const typename A<T>::B &lhs, const typename A<T>::B &rhs);

template <typename T>
bool
operator!=(const typename A<T>::B &lhs, const typename A<T>::B &rhs);

template <typename T>
class A<T>::B
{
public:
friend bool
operator==<>(const B &lhs, const B &rhs);

friend bool
operator!=<>(const B &lhs, const B &rhs);
};

template <typename T>
bool
operator==(const typename A<T>::B &lhs, const typename A<T>::B &rhs)
{
return true;
}

template <typename T>
bool
operator!=(const typename A<T>::B &lhs, const typename A<T>::B &rhs)
{
return false;
}

int
main()
{
A<int>::B b;
b == b;

}

regards,
Alex
 
V

Victor Bazarov

Alexander Stippler said:
what's wrong about the following code? It does not compile.

Several things are wrong. However, I'd like to know what prevented
you from posting the compiler diagnostic?
template <typename T>
class A {
public:
class B;
};

template <typename T>
bool
operator==(const typename A<T>::B &lhs, const typename A<T>::B &rhs);

template <typename T>
bool
operator!=(const typename A<T>::B &lhs, const typename A<T>::B &rhs);

template <typename T>
class A<T>::B
{
public:
friend bool
operator==<>(const B &lhs, const B &rhs);

If you need a particular instantiation to be a friend, you expect that
'T' is going to be determined here. It won't. The language does not
allow template argument deduction from nested types in templates. You
have to specify the T:

friend bool operator==<T>(...

..
friend bool
operator!=<>(const B &lhs, const B &rhs);

Same here.
};

template <typename T>
bool
operator==(const typename A<T>::B &lhs, const typename A<T>::B &rhs)
{
return true;
}

template <typename T>
bool
operator!=(const typename A<T>::B &lhs, const typename A<T>::B &rhs)
{
return false;
}

int
main()
{
A<int>::B b;
b == b;

Now, this is not going to be resolved. Again, because the compiler
does not know how to deduce type arguments from nested types, you
need to help it:

operator==<int>(b,b);

Ugly? Yes. But there is no other way. Perhaps you need to think
of making your operator== and operator!= templates based on B and
not on T:

template<typename B> bool operator==(B const&, B const&);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top