'operator== for classes inside a variadic template class

I have the following class structure:

template <typename...>
class SomeClass {
public:
    class Foo {  };
    class Bar {  };
};

I need to define operator== for SomeClass<Ts...>::Foo and SomeClass<Ts...>::Bar and I need to make it a friend of both Foo and Bar. The closest I got this to working is the following:

template <typename...>
class SomeClass {
public:
    class Bar;
    class Foo {
        
        friend bool operator==(const Foo&, const Bar&) { 
            return true;
        }
    };
    class Bar { 
        
        friend bool operator==(const Foo&, const Bar&);
    };
};

Then I do:

SomeClass<int, double>::Foo foo;
SomeClass<int, double>::Bar bar;
foo == bar;

This compiles and works fine except for the fact that gcc gives me the warning:

warning: friend declaration `bool operator==(const SomeClass<Args>::Foo&, const SomeClass<Args>::Bar&)` declares a non-template function
note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)

I kind of understand why this happens (operator== indeed depends on the template parameters of SomeClass), but how do I get rid of it? Adding <> to the second friend declaration, as suggested, only breaks compilation: the friending is no longer recognized and the compiler complaints about access to a private member.

I tried to modify the code according to the template friend declaration guide, but that only made things worse:

template <typename...>
class SomeClass;

template <typename... Args>
bool operator==(const typename SomeClass<Args...>::Foo&, 
                const typename SomeClass<Args...>::Bar&);

template <typename... Args>
class SomeClass {
public:
    class Bar;
    class Foo {
        
        friend bool operator==<Args...>(const Foo&, const Bar&);
    };
    class Bar { 
        
        friend bool operator==<Args...>(const Foo&, const Bar&);
    };
};

template <typename... Args>
bool operator==(const typename SomeClass<Args...>::Foo&, 
                const typename SomeClass<Args...>::Bar&) {
    return true;
}

Now the weirdest thing happens when I call foo == bar:

error: no match for ‘operator==’ (operand types are ‘SomeClass<int, double>::Foo’ and ‘SomeClass<int, double>::Bar’)
note: candidate: ‘bool operator==(const typename SomeClass<Args ...>::Foo&, const typename SomeClass<Args ...>::Bar&) [with Args = {}; typename SomeClass<Args ...>::Foo = SomeClass<>::Foo; typename SomeClass<Args ...>::Bar = SomeClass<>::Bar]’ (reversed)
note: no known conversion for argument 1 from ‘SomeClass<int, double>::Bar’ to ‘const SomeClass<>::Foo&’

I.e. for some weird reason it tries to call the template specification with an empty arguments list and fails. Changing the operator type (to operator+) doesn't help (my idea was, this had something to do with C++20 new rules for comparison operators, but no).

So the questions I have are:

  1. What's going on? I'm kind of confused, especially by the second part: why would the compiler try to call the operator for an empty parameter pack?
  2. How do I avoid the warning in the first solution?
  3. How do I define the operator outside of the class definition properly?


Solution 1:[1]

Ok, here are the results of some research I did.

In case of the friend in-class definition, according to cppreference, what it does is it generates non-template overloads of operator==. Thus, it is perfectly fine to reference them from the second friend declaration, and the code itself is correct. This is also why adding "<>" breaks the befriending: the overloads generated by the first definition are not template functions, while the second definition with the "<>" added now refers to some template overload that isn't definded.

Both Clang and MSVC compile that code without any problems, so the warning seems to be a GCC-only thing. I think, it is ok to suppress it.

The alternative would be to make the operator into a template, but unfortunately doing this properly for the parent class template parameters is impossible. This won't compile (see below why):

template <typename...>
class SomeClass {
public:
    class Bar;
    class Foo {
        
        template <typename... Ts>
        friend bool operator==(const typename SomeClass<Ts...>::Foo&, 
                               const typename SomeClass<Ts...>::Bar&) { 
            return true;
        }
    };
    class Bar { 
        template <typename... Ts>
        friend bool operator==(const typename SomeClass<Ts...>::Foo&, 
                               const typename SomeClass<Ts...>::Bar&);
    };
};

The real alternative here is to trick GCC by making the operator template with some obsolete arguments, that could be deduced. And since default template arguments are forbidden in friend declarations, the only other hack I can think of is to make the operator variadic and use the fact that a trailing parameter pack that is not otherwise deduced, is deduced to an empty parameter pack. This works and emits no warnings in GCC:

template <typename...>
class SomeClass {
public:
    class Bar;
    class Foo {
        
        template <typename...>
        friend bool operator==(const Foo&, const Bar&) { 
            return true;
        }
    };
    class Bar { 
        template <typename...>
        friend bool operator==(const Foo&, const Bar&);
    };
};

I really see no reason in doing that now, so the best thing to do is to pretend that you never saw this, and that I never wrote this.


Now, the second part, the outside definition. The problem here is that, as it turns out, there is no way in C++ to deduce template arguments (pack or not) of a parent class from a nested class.

I.e. a thing like this cannot possibly work:

template <typename T>
void foo(typename Parent<T>::Child) { }

foo(Parent<int>::Child{});

There even was a proposal to resolve this issue, but it was declined.

Defining operator== as a template function in my example above has exactly this problem: once the operator is called for SomeClass<int, double>::Foo and SomeClass<int, double>::Bar, the argument deduction is impossible (though the definition itself is correct), thus the compilation fails. This is also the answer to my first question: since the deduction is impossible, a parameter pack is deduced as an empty pack. Not at all what I intended.

The only workaround I came up with is to define the operator for the template non-nested arguments, and then restrict them. I am going to use C++20 concepts for this, although I think a SFINAE solution could be just as fine.

This works exactly as intended:

template <typename...>
class SomeClass;

template <typename T>
constexpr bool IsSomeClass = false;

template <typename... Args>
constexpr bool IsSomeClass<SomeClass<Args...>> = true;

template <typename T, typename U>
concept IsProperFooBar = requires {
  typename T::Parent;
  typename U::Parent;
  requires std::same_as<typename T::Parent, typename U::Parent>;
  requires IsSomeClass<typename T::Parent>;
  requires std::same_as<std::decay_t<T>, typename T::Parent::Foo>;
  requires std::same_as<std::decay_t<U>, typename U::Parent::Bar>;
};

template <typename T, typename U> requires IsProperFooBar<T, U>
bool operator==(const T&, const U&);

template <typename... Args>
class SomeClass {
public:
    class Foo {
    public:
      using Parent = SomeClass;

    private:
      template <typename T, typename U> requires IsProperFooBar<T, U>
      friend bool operator==(const T&, const U&);
    };

    class Bar {
    public:
      using Parent = SomeClass;

    private:
      template <typename T, typename U> requires IsProperFooBar<T, U>
      friend bool operator==(const T&, const U&);
    };
};

template <typename T, typename U> requires IsProperFooBar<T, U>
bool operator==(const T&, const U&) {
    return true;
}

The only issue I see with this solution is that there is now a universal template operator==, so the concept will be checked every time you call == for anything, which may slow down compilation and emit unnecessary concept-not-satisfied diagnostic messages for other things. On the plus side, there is no need in forward-declaring class Bar anymore, so at least I got that going for me, which is nice :-)

Solution 2:[2]

I got this solution with operator=='s definition outside the class. There is no warning now, but I had to remove the friend qualifier. In order to access Foo's private methods from Bar's functions, declare Bar a friend of Foo (inside Foo). Do likewise for Bar if you want to access Bar's members from within Foo's methods.

Perhaps its a step forward. Hopes this helps.

#include <iostream>

template <typename... Args>
class SomeClass {
public:
    class Bar;
    class Foo;
    
    class Foo {
    public:
        friend Bar;
        bool operator==(const Bar&) const;

        void do_something_to_Bar(Bar&);

    private:
        int _foo;
    };

    class Bar {
    public:
        friend Foo;
        bool operator==(const Foo&) const;

        void do_something_to_Foo(Foo&);

    private:
        int _bar;
    };
    
};

template<typename... Args>
bool SomeClass<Args...>::Foo::operator== (const Bar& b) const {
    return b._bar == _foo;
}

template<typename... Args>
bool SomeClass<Args...>::Bar::operator== (const Foo& f) const {
    return f == *this;
}

template<typename... Args>
void SomeClass<Args...>::Bar::do_something_to_Foo(Foo& f) {
    f._foo = 4;
    _bar = 4;
}

template<typename... Args>
void SomeClass<Args...>::Foo::do_something_to_Bar(Bar& b) {
    b._bar = 4;
    _foo = 3;
}

int main() {
    SomeClass<int,float>::Foo foo;
    SomeClass<int,float>::Bar bar;
    
    foo.do_something_to_Bar(bar);
    std::cout << (foo == bar) << '\n';
    std::cout << (bar == foo) << '\n';

    bar.do_something_to_Foo(foo);
    std::cout << (foo == bar) << '\n';
    std::cout << (bar == foo) << '\n';
}

The definition of SomeClass<Args...>::Bar::operator== does not redefine the operator, but rather uses the definition of SomeClass<Args...>::Foo::operator==.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2