How to properly declare a friend of a nested class of a template class?

前端 未结 2 678
予麋鹿
予麋鹿 2020-12-19 10:54

When I do the following:

template 
class Container
{
public:
    class Iterator
    {
        friend bool operator==(const Iterator& x,         


        
2条回答
  •  粉色の甜心
    2020-12-19 11:34

    It's warning about the fact that it is going to be virtually impossible to define that operator== out-of-class.

    That is to say, that friend declaration befriends a non-template operator== function - for example, Container::Iterator has as a friend the function

    bool operator==(const Container::Iterator&, const Container::Iterator&);
    

    This function is not a template, so there's pretty much no way to define operator== for all possible Containers outside the class template definition.

    If you try to do

    template
    bool operator==(const Container::Iterator&, const Container::Iterator&);
    

    That's a function template, and doesn't match the friend declaration. (In this case it's even worse, as you can't actually use this operator because T is in a non-deduced context.)

    The warning message suggests one possible fix - first declaring a function template and then befriending a specialization of it. (You'll need to pull Iterator out of the class into its own separate class template so that T can be deduced.) The other possible fix is to just define the function inside the class template definition.

提交回复
热议问题