By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,124 Members | 1,578 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,124 IT Pros & Developers. It's quick & easy.

nested classes and friend declaration

P: n/a
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
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Alexander Stippler" <st**@mathematik.uni-ulm.de> wrote...
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&);

and then specialise them for A<T>::B if needed...

}

regards,
Alex

Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.