Non-member operator overloading of inner class templates - c++

I prefer to write definitions for class and function templates in a separate file which is automatically included after the "public" header. However, I've come to an interesting case where it looks like I can't do that.
template <typename T>
class Outer
{
public:
template <typename U>
class Inner
{
friend bool operator ==(const Inner& lhs, const Inner& rhs);
};
};
using Type = Outer<int>::Inner<short>;
int main()
{
Type a;
Type b;
a == b;
}
Is it possible to write definition of operator== separately that will work for any T and U?

For a particular specialization, yes:
template <typename T>
class Outer
{
public:
template <typename U>
class Inner
{
int x = 42;
friend bool operator ==(const Inner& lhs, const Inner& rhs);
};
};
using Type = Outer<int>::Inner<short>;
bool operator ==(const Type& lhs, const Type& rhs) {
return lhs.x == rhs.x;
}
int main()
{
Type a;
Type b;
a == b;
}
In your example, each specialization of the template befriends a non-template function that takes that particular specialization as parameters. You could define this function in-class (and then it will be stamped out every time the template is instantiated), or you could define it out-of-class - but then you would have to define one for every specialization you ever use.

As Igor Tandetnik points out, your example declares a non-template friend function, which you'll have to overload for each template instantiation, which is one reason friend functions are allowed to be defined inline (so they can be generated by the template without having to be templates themselves).
If you want to define the friend function as a template, here is the closest I was able to come up with:
template <typename T>
struct Outer {
template <typename U>
struct Inner;
};
template<typename T, typename U>
bool operator==( typename Outer<T>::template Inner<U> const &, typename Outer<T>::template Inner<U> const & );
template <typename T>
template <typename U>
struct Outer<T>::Inner {
friend bool operator==<T,U>(Inner const &, Inner const &);
};
template<typename T, typename U>
bool operator==( typename Outer<T>::template Inner<U> const &, typename Outer<T>::template Inner<U> const & ) {
return true;
}
// I switched this out, because my gcc-4.6 doesn't
// understand "using" aliases like this yet:
typedef Outer<int>::Inner<short> Type;
int main() {
Type a;
Type b;
operator==<int,short>( a, b );
}
Unfortunately, you'll notice the call site of this operator function is very awkward: operator==<int,short>( a, b ). I believe defining a function template on a nested class template like this disables (or at least interferes with) argument deduction, so you have to specify the template parameters explicitly (which means calling it as a function rather than in operator form). This is why the inline friend definition is so convenient. If you really want to define your operator=='s code separately, I'd recommend defining the friend inline to call another function template (with the proper template arguments), which you can then define out-of-line as a free function.

Related

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:
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?
How do I avoid the warning in the first solution?
How do I define the operator outside of the class definition properly?
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 :-)
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==.

Template Friend Function / Class forward declaration

Why do we need template forward declaration for BlobPtr and operator overloading for template.
template <typename> class BlobPtr;
template <typename> class Blob;
template <typename T>
bool operator==(const Blob<T>&, const Blob<T>&);
template <typename T>
class Blob {
friend class BlobPtr<T>;
friend bool operator==<T>
(const Blob<T>&, const Blob<T>&);
};
class BlobPtr<T>{};
Blob<char> ca;
Blob<int> ia;
For for nontemplate class, forward declaration is not needed.
class Blob {
type
class BlobPtr;
friend bool operator==
(const Blob&, const Blob&);
};
class BlobPtr{};
If you want to declare the template in a friend declaration, you can just do that, you don't need forward declarations:
template <typename T>
class Blob {
template <typename U>
friend class BlobPtr;
template <typename U>
friend bool operator==(const Blob<U>&, const Blob<U>&);
};
This declares all instances of the templates as friends, not just the matching one. That is, BlobPtr<int> and BlobPtr<long> (and generally BlobPtr<Anything>) are all friends of Blob<int>.
If you want to declare a particular specialization of a template as a friend (so that BlobPtr<int> is a friend of Blob<int> but BlobPtr<long> is not), then you first need to tell the compiler that BlobPtr is a template in the first place - that's what you need forward declaration for.

Force instantiation of friend functions

Assume we have a template class with friend function:
template<class T>
class A {
friend A operator+ (int, const A&);
};
This function is implemented somewhere below:
template<class T>
A<T> operator+ (int i, const A<T>& a) {
...
}
And also there is force instantiation of class template further below:
template class A<int>;
Does this imply that operator+(int, A<int>) will be compiled? Or do I have to force instantiate it separately to achieve that?
Template parameters aren't automatically forwarded to friend declarations. You need to specify a template parameter for the function as well:
template<class T>
class A {
template<class U>
friend A<U> operator+ (int, const A<U>&);
};
Implementation is almost correct, should be
template<class T>
A<T> operator+ (int i, const A<T>& a) {
// ^^^
// ...
}

How to force a compiler to choose a specific function specialization

For example, I have two classes:
class Foo {
public:
const bool operator==(const Foo&) const;
template<class _Ty>
const bool operator==(const _Ty&) const;
};
class Bar : public Foo { };
And code like this:
Foo& foo;
Bar& bar;
const bool equality = (foo == bar);
Obviously, a compiler will choose the template function to evaluate this expression because variable bar need to be converted to Foo& to call the specialized operator==. But is there any way how I can force a compiler (without casting Bar& into Foo&) to choose the specialization firstly instead of the template function when the argument is an instance of a class derived from Foo (e.g. add/remove some modifiers or something else)?
Is there any way how I can force a compiler (without casting Bar& into Foo&) to choose the specialization firstly instead of the template function when the argument is an instance of a class derived from Foo?
Yes, you can, using type traits. Specifically you can use std::enable_if and std::is_base_of as follows:
template<typename Type>
typename std::enable_if<
std::is_base_of<Foo, Type>::value,
const bool
>::type
operator==(const Type&) const { … }
template<typename Type>
typename std::enable_if<
!std::is_base_of<Foo, Type>::value,
const bool
>::type
operator==(const Type&) const { … }
Live demo
You basically activate/deactivate an overload based on template argument.
You can also make things slightly more readable by adding an alias:
template<class Type>
using is_fooable = std::is_base_of<Foo, Type>;
Live demo

C++ error C2801: 'operator =' must be a non-static member

I am trying to overload the operator= in a template class.
I have this template class:
template <class T>
class Matrice
{
T m,n;
public:
template <class V>
friend Matrice<V>& operator=(const Matrice<V> &);
};
template <class T>
Matrice<T>& Matrice<T>::operator=(const Matrice<T> &M)
{
/*...*/
return *this;
}
and I also tried:
template <class T>
class Matrice
{
T m,n;
public:
template <class V>
Matrice<V>& operator=(Matrice<V> &);
};
template <class T>
Matrice<T>& operator=(Matrice<T> &M)
{
/*...*/
return *this;
}
but I still get this error:
error C2801: 'operator =' must be a non-static member
error C2801: 'operator =' must be a non-static member
The bolded word is key here. friend is not a member; it's a friend. Remove that friend keyword and treat operator= as member:
The syntactically proper version is:
template <class T>
class Matrice
{
T m,n;
public:
template <class V>
Matrice<V>& operator=(const Matrice<V> &);
};
template <class T>
template <class V>
Matrice<V>& Matrice<T>::operator=(const Matrice<V> &M)
{
/*...*/
return *this;
}
Although I think that it's wrong to use that template <class V> there; the sematically proper version would be
template <class T>
class Matrice
{
T m,n;
public:
Matrice<T>& operator=(const Matrice<T> &);
};
template <class T>
Matrice<T>& Matrice<T>::operator=(const Matrice<T> &M)
{
/*...*/
return *this;
}
Explanation: you don't generally want to assign Type<V> to Type<T> in this way; if you have to, then it is probably sign of bad design.
The standard says
12.8 Copying and moving class objects [class.copy]
...
17 A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.
A friend function doesn't fulfill these requirements. It must be a member function.
To address the comments that this is just "plain" assignment, not copy assignment, let's add another quote from the standard:
13.5.3 Assignment [over.ass]
An assignment operator shall be implemented by a non-static member function with exactly one parameter.
In standardese, "shall" doesn't leave any options to do anything else.
You mixed friend and member declarations and definitions: in the first example you declared operator= as a friend but defined it as a class member. In the second example, you declared operator= as a member but tried to define it as a non-member. Your operator= has to be a member (see this question why) and you can do the following:
template <class T>
class Matrice
{
T m,n;
public:
Matrice<T>& operator=(Matrice<T> &);
};
template <class T>
Matrice<T>& Matrice<T>::operator=(Matrice<T> &M)
{
/*...*/
return *this;
}