operator== for classes inside a variadic template class - c++

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==.

Related

C++ template class, template member friend function matching rules

I have a templated class with a templated friend function declaration that is not having its signature matched when stated in a more direct, but seemingly equivalent, expression:
link to example on online compiler
#include <type_traits>
template <typename Sig> class Base;
template <typename R, typename ... Args> class Base<R(Args...)> { };
template <typename Sig, typename T> class Derived;
template <typename Sig> struct remove_membership;
template <typename T, typename R, typename ... Args>
class Derived<R(Args...), T> : public Base<R(Args...)> {
static void bar() { }
// XXX: why are these two not equivalent, and only the 1st version successful?
template <typename T2>
friend auto foo(T2 const &) -> Base<typename
remove_membership<decltype(&std::remove_reference_t<T2>::operator())>::type> *;
template <typename T2>
friend auto foo(T2 const &) -> Base<R(Args...)> *;
};
template <typename F, typename R, typename ... Args>
struct remove_membership<R (F::*)(Args...) const> {
using type = R(Args...);
};
template <typename T>
auto foo(T const &) -> Base<typename
remove_membership<decltype(&std::remove_reference_t<T>::operator())>::type> *
{
using base_param_t = typename remove_membership<
decltype(&std::remove_reference_t<T>::operator())>::type;
Derived<base_param_t, T>::bar();
return nullptr;
}
int main(int, char **) { foo([](){}); } // XXX blows up if verbose friend decl. removed.
Inside member definitions of Derived<R(Args...), T> (for example, in the body of bar()), the types match, adding to my confusion:
static_assert(std::is_same<Base<R(Args...)>, Base<typename
remove_membership<decltype(&std::remove_reference_t<T>::operator())>::type>>::value,
"signature mismatch");
Are there rules around template class template member function (and friend function) delarations and instantiations that make these preceding declarations distinct in some or all circumstances?
template <typename T2>
void foo(T2 const &)
template <typename T2>
auto foo(T2 const &)
-> std::enable_if_t<some_traits<T2>::value>;
Are 2 different overloads. Even if both return void (when valid).
2nd overload uses SFINAE.
(and yes, template functions can differ only by return type contrary to regular functions).
Your version is not identical but similar (&std::remove_reference_t<T>::operator() should be valid)
You can use the simpler template friend function:
template <typename T, typename R, typename ... Args>
class Derived<R(Args...), T> : public Base<R(Args...)> {
static void bar() { }
template <typename T2>
friend auto foo(T2 const &) -> Base<R(Args...)>*;
};
template <typename T>
auto foo(T const &) -> Base<void()>* // friend with Derived<void(), U>
{
using base_param_t = typename remove_membership<
decltype(&std::remove_reference_t<T>::operator())>::type;
Derived<base_param_t, T>::bar();
return nullptr;
}
Demo
but you have then to implement different version of the template foo.
The problem can be reduced to:
template<class T>
struct identity {
using type=T;
};
class X {
int bar();
public:
template<class T>
friend T foo();
};
template<class T>
typename identity<T>::type foo() { return X{}.bar(); }
int main() {
foo<int>(); // error: bar is a private member of X
}
Even though we know identity<T>::type is always T, the compiler doesn't know that and would be wrong to assume so. There could be a specialization of identity<T> somewhere later in the code that resolves to some type other than T.
Therefore when the compiler sees the second declaration of foo it won't assume that it is the same friend foo declared before.

Having Pointer Template and Pointer To Member Function as Template Arguments in C++03

I want to define a template class with 2 template arguments:
A pointer type T*
A pointer to a member function of the underlying type T
Additionally I would like to set a default method for the function argument.
// Do not allow SortedLinkedList<T>
template<typename T, bool (T::* comparisonMethod)(const T&) = &T::lessEqual>
class SortedLinkedList
{
private:
SortedLinkedList();
};
// Allow SortedLinkedList<T*>
template<typename T, bool (T::* comparisonMethod)(const T&)>
class SortedLinkedList<T*>
{
public:
void insert(T* item)
{
// do something with /item->*comparisonMethod)(...))
}
};
This code does not compile, because g++ (4.4.3) can not deduce the underlying type of T*
error: creating pointer to member function of non-class type ‘T*’
Is there a way to deduce the underlying type already in the class declaration? decltype is not available in C++03 and I don't know if it would work at this place.
I've found this answer, but it does not help in this case.
Thanks
The Problem
The reason it fails to compile is that the compiler will check to see that the primary-template is a viable match before it goes on to see if there is any specialization that is a more suitable alternative.
This means that when you try to instantiate SortedLinkedList<A*>, the compiler tries to see if the declaration bool (T::* comparisonMethod)(const T&) = &T::lessEqual, in the primary-template, is well-formed having T = A* - which it obviously isn't (since pointers can't have member-functions).
A Solution
One way to solve this issue is to add a level of indirection, so that both the primary template - and the specialization - yields a well-formed instantiation.
template<class T> struct remove_pointer { typedef T type; };
template<class T> struct remove_pointer<T*> { typedef T type; };
template<class T>
struct comparison_method_helper {
typedef typename remove_pointer<T>::type Tx;
typedef bool (Tx::*type)(Tx const&) const;
};
// primary-template
template<
class T,
typename comparison_method_helper<T>::type = &remove_pointer<T>::type::lessEqual
> class SortedLinkedList;
// specialization
template<typename T, typename comparison_method_helper<T>::type func>
class SortedLinkedList<T*, func> {
public:
void insert (T const& item) {
(item.*func) (T ());
}
};
#include <iostream>
struct A {
bool lessEqual (A const&) const {
std::cerr << "hello world\n";
return false;
}
};
int main () {
SortedLinkedList<A*> ().insert (A()); // outputs 'hello world'
}

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

Non-member operator overloading of inner class templates

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.

SFINAE to enable nontemplate member function

This is probably a duplicate, but I just can't find one where the OP clearly has the same problem I'm having.
I have a class, and I'm trying to enable operator- only if the class template parameter is not an unsigned type.
#include <type_traits>
template<class T>
struct A {
typename std::enable_if<!std::is_unsigned<T>::value,A>::type operator-() {return {};}
};
int main() {
A<unsigned> a=a;
}
Unfortunately, this produces a compiler error any time I instantiate it with an unsigned type as shown.
main.cpp:5:29: error: no type named 'type' in 'std::enable_if<false, A<unsigned int> >'; 'enable_if' cannot be used to disable this declaration
typename std::enable_if<!std::is_unsigned<T>::value,A>::type operator-() {return {};}
^~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:9:17: note: in instantiation of template class 'A<unsigned int>' requested here
A<unsigned> a=a;
^
Well, I can clearly see that enable_if is not going to work here. One vaguely similar question mentioned I can use inheritance and template specialization to work around this, but... is there really no better way?
I had the same problem once. Turns out there can't be a substitution failure since the default template argument doesn't depend on a template parameter from the function template. You have to have a template argument defaulted to the enclosing template type, like this:
template<typename U = T,
class = typename std::enable_if<!std::is_unsigned<U>::value, U>::type>
A operator-() { return {}; }
A bit long for a comment: You can also use a free function, even for unary operators.
#include <type_traits>
template<class T>
struct A {
};
template<class T>
typename std::enable_if<!std::is_unsigned<T>::value,A<T>>::type
operator-(A<T>) {return {};}
int main() {
A<signed> b;
-b; // ok
A<unsigned> a;
-a; // error
}
This doesn't introduce a member function template for each class template.
Here's how you can befriend it:
template<class T>
class A {
int m;
public:
A(T p) : m(p) {}
template<class U>
friend
typename std::enable_if<!std::is_unsigned<U>::value,A<U>>::type
operator-(A<U>);
};
template<class T>
typename std::enable_if<!std::is_unsigned<T>::value,A<T>>::type
operator-(A<T> p) {return {p.m};}
int main() {
A<signed> b(42);
-b; // ok
A<unsigned> a(42);
//-a; // error
}
You can (should) forward-declare that function template, though.
One possible way is introducing a dummy template parameter:
template<class T>
struct A {
template<
typename D = int,
typename = typename std::enable_if<!std::is_unsigned<T>::value, D>::type
>
A operator-() {return {};}
};
There is a long way using inheritance:
template <class T>
struct A;
template <class T, bool = std::is_unsigned<T>::value>
struct MinusOperator
{
A<T> operator-()
{
A<T>* thisA = static_cast<A<T>*>(this);
// use thisA instead of this to get access to members of A<T>
}
};
template <class T>
struct MinusOperator<T, true> {};
template <class T>
struct A : MinusOperator<T>
{
friend struct MinusOperator<T>;
};