I am trying to implement an overload for operator!= that compares two objects of different types (InnerA and InnerB). Both of the types are defined as nested classes within a template class (Outer). The overload needs to be a friend of both classes as it accesses private fields from each.
template<typename Type> class Outer
{
public:
class InnerA;
class InnerB;
};
template<typename Type> bool operator!=(const typename Outer<Type>::InnerA& lhs, const typename Outer<Type>::InnerB& rhs);
template<typename Type> class Outer<Type>::InnerA
{
const int val = 0;
friend bool operator!=<>(const InnerA& lhs, const typename Outer<Type>::InnerB& rhs);
};
template<typename Type> class Outer<Type>::InnerB
{
const int val = 1;
friend bool operator!=<>(const typename Outer<Type>::InnerA& lhs, const InnerB& rhs);
};
template<typename Type> bool operator!=(const typename Outer<Type>::InnerA& lhs, const typename Outer<Type>::InnerB& rhs)
{
return lhs.val != rhs.val;
}
int main()
{
bool b = Outer<int>::InnerA() != Outer<int>::InnerB();
}
The above code fails to compile, emitting:
In instantiation of 'class Outer<int>::InnerA':
34:33: required from here
15:17: error: template-id 'operator!=<>' for 'bool operator!=(const Outer<int>::InnerA&, const Outer<int>::InnerB&)' does not match any template declaration
In instantiation of 'class Outer<int>::InnerB':
34:57: required from here
22:17: error: template-id 'operator!=<>' for 'bool operator!=(const Outer<int>::InnerA&, const Outer<int>::InnerB&)' does not match any template declaration
In function 'int main()':
34:35: error: no match for 'operator!=' (operand types are 'Outer<int>::InnerA' and 'Outer<int>::InnerB')
34:35: note: candidate is:
26:30: note: template<class Type> bool operator!=(const typename Outer<Type>::InnerA&, const typename Outer<Type>::InnerB&)
26:30: note: template argument deduction/substitution failed:
34:57: note: couldn't deduce template parameter 'Type'
While there might be better ways to achieve a similar result, I'm curious as to what precisely is wrong with my code. Thanks!
template<typename Type> class Outer<Type>::InnerA
{
friend bool operator!=(const InnerA& lhs, const typename Outer<Type>::InnerB& rhs) { return true; }
};
template<typename Type> class Outer<Type>::InnerB
{
friend bool operator!=(const typename Outer<Type>::InnerA& lhs, const InnerB& rhs) { return true; }
};
these are non-template friends. They also conflict. So implement one of them, omit the other.
They will be found via ADL.
I found the following workaround, refactoring the overload as a method of one of the nested classes:
template<typename Type> class Outer
{
public:
class InnerA;
class InnerB;
};
template<typename Type> class Outer<Type>::InnerA
{
const int val = 0;
public:
bool operator!=(const typename Outer<Type>::InnerB& other);
};
template<typename Type> class Outer<Type>::InnerB
{
const int val = 1;
friend bool Outer<Type>::InnerA::operator!=(const InnerB& other);
};
template<typename Type> bool Outer<Type>::InnerA::operator!=(const typename Outer<Type>::InnerB& other)
{
return val != other.val;
}
int main()
{
bool b = Outer<void>::InnerA() != Outer<void>::InnerB();
}
However, I am still curious if the same can be accomplished using a non-member friend function as in the question.
The issue with the code in the question ended up being that template deduction is not attempted on type names nested inside a dependent type (e.g. Outer<Type>::Inner).
This question is essentially a duplicate of Nested template and parameter deducing. A detailed explanation on why this is a problem can be found here.
Related
In this code, why is it not possible to access the private field of my class in the operator overload ?
(Note that this is only a MRE, not the full code)
template <typename T>
class Frac
template <typename T, typename U>
Frac<T> operator+ (Frac<T> lhs,const Frac<U>& rhs);
template <typename T, typename U>
bool operator==(const Frac<T>& lhs, const Frac<U>& rhs);
template <typename T>
class Frac {
template<typename>
friend class Frac;
friend Frac operator+ <>(Frac lhs,const Frac& rhs);
friend bool operator== <>(const Frac& lhs, const Frac& rhs);
private:
T numerator, denominator;
};
template <typename T, typename U>
Frac<T> operator+(Frac<T> lhs,const Frac<U>& rhs) {
lhs.denominator += rhs.denominator;
return lhs;
}
template <typename T, typename U>
bool operator==(const Frac<T>& lhs, const Frac<U>& rhs) {
return (lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator);
}
When I compile the compiler tells me that it is not possible to access the denominator and numerator fields because they are private. However the overload is indicated as friendly. The class is also indicated as friendly so that all instances of the class whatever the type are friendly.
Could someone explain me what the problem is and how to solve it?
To make each instance of
template <typename T, typename U>
bool operator==(const Frac<T>& lhs, const Frac<U>& rhs);
a friend, you need to be just as verbose in your friend declaration. Copy this declaration and stick "friend" in it. There are two quirks. First, template has to come before friend, so you'll be adding the keyword in the middle of the declaration. Second, T is already being used as the template parameter to the class, so you should choose a different identifier to avoid shadowing (I'll use S).
template <typename S, typename U>
// ^^^
friend bool operator==(const Frac<S>& lhs, const Frac<U>& rhs);
// ^^^^^^ ^^^
Without this change, you are saying that the friend of Frac<T> is an operator that takes two Frac<T> parameters (the same T).
it is not possible to access the denominator and numerator fields because they are private.
Yes, you haven't made the free functions friends. You've made the classes friends, but that doesn't help the free functions. One simpler solution is to define them in the class definition.
Example:
template <typename U>
friend Frac operator+(Frac lhs, const Frac<U>& rhs) {
lhs.denominator += rhs.denominator;
return lhs;
}
However, operator+ could be implemented as a free function without any friendship if you instead make operator+= a member function. The friendship between all Frac<>s has already been established so no additional friend declarations are needed.
Example:
#include <iostream>
#include <utility>
template <typename T>
class Frac {
public:
template <typename> // be friends with all Frac's
friend class Frac;
Frac() = default; // needed because for the templated converting ctor below
// a converting constructor from any Frac:
template<class U>
explicit Frac(const Frac<U>& rhs) :
numerator(rhs.numerator), denominator(rhs.denominator) {}
template <typename U>
Frac& operator+=(const Frac<U>& rhs) {
denominator += rhs.denominator; // ok: rhs has befriended Frac<T>
return *this;
}
template <typename U>
bool operator==(const Frac<U>& rhs) const {
// ok: rhs has befriended Frac<T> here too
return numerator == rhs.numerator && denominator == rhs.denominator;
}
private:
T numerator{}, denominator{};
};
// This free function doesn't need to be a friend. It uses the member function
// operator+=
// The returned type, Fact<R>, is deduced by fetching the type you'd gotten
// if you add a T and U.
template<typename T, typename U,
typename R = decltype(std::declval<T>() + std::declval<U>())>
Frac<R> operator+(const Frac<T>& lhs, const Frac<U>& rhs) {
Frac<R> rv(lhs); // use the converting constructor
rv += rhs;
return rv;
}
int main() {
Frac<int> foo;
Frac<double> bar;
auto r = foo + bar; // r is a Frac<double> (int + double => double)
}
I'm developing a header-only library for automatic/algorithmic differentiation. The goal is to be able to simply change the type of the variables being fed to a function and calculate first and second derivatives. For this, I've created a template class that allows the programmer to select the storage type for the private data members. Included is a snippet below with an offending operator overload.
template <typename storage_t>
class HyperDual
{
template <typename T> friend class HyperDual;
public:
template <typename T>
HyperDual<storage_t> operator+(const HyperDual<T>& rhs) const
{
HyperDual<storage_t> sum;
for (size_t i = 0; i < this->values.size(); i++)
sum.values[i] = this->values[i] + rhs.values[i];
return sum;
}
protected:
std::vector<storage_t> values;
};
Later on, to maximize the versatility, I provide template functions to allow interaction.
template <typename storage_t, typename T>
HyperDual<storage_t> operator+(const HyperDual<storage_t>& lhs, const T& rhs)
{
static_assert(std::is_arithmetic<T>::value && !(std::is_same<T, char>::value), "RHS must be numeric");
return HyperDual<storage_t>(lhs.values[0] + rhs);
}
template <typename storage_t, typename T>
HyperDual<storage_t> operator+(const T& lhs, const HyperDual<storage_t>& rhs)
{
static_assert(std::is_arithmetic<T>::value && !(std::is_same<T, char>::value), "LHS must be numeric");
return HyperDual<storage_t>(lhs + rhs.values[0]);
}
What I'm encountering is that the compiler is trying to instantiate the second non-member template function.
#include "hyperspace.h"
int main()
{
HyperDual<long double> one(1); // There is an appropriate constructor
HyperDual<double> two(2);
one + two;
return 0;
}
I get the static_assert generated error "LHS must be numeric" for this. How would I resolve the ambiguity?
use enable_if_t to make the non-member template can only be applied in the specific context?
template <typename storage_t, typename T, typename = enable_if_t<std::is_arithmetic<T>::value && !(std::is_same<T, char>::value)>>
HyperDual<storage_t> operator+(const HyperDual<storage_t>& lhs, const T& rhs)
{
static_assert(std::is_arithmetic<T>::value && !(std::is_same<T, char>::value), "RHS must be numeric");
return HyperDual<storage_t>(lhs.values[0] + rhs);
}
the static_assert may be duplicated here.
Ok. I found my own issue. It comes down to the difference between static_assert and std::enable_if
Replacing my template declaration and removing static_assert, I achieve equivalent functionality:
template <typename storage_t, typename T,
typename = typename std::enable_if<std::is_arithmetic<T>::value && !std::is_same<T, char>::value>::type>
HyperDual<storage_t> operator+(const T& lhs, const HyperDual<storage_t>& rhs)
{
return HyperDual<storage_t>(lhs + rhs.value());
}
(Small detail, but rhs.values[0] was replaced with rhs.value(). This had nothing to do with the template issue, but was related to member access.
EDIT: Prolog: I'm a victim of my own ignorance and also of late-night coding.
I'm writing a templated class using template template. It has an iterator, which means that I need to provide an appropriately templated operator==(). This is where I'm having trouble.
Representative code sample follows:
#include <iostream>
#include <typeinfo>
using namespace std;
namespace detail {
template <typename T> class foo {};
template <typename T> class bar {};
}
template <template<class> class A, template<class> class B>
struct basic_thing {
template <typename T> using target_type = A<B<T>>;
target_type<float> fmember;
target_type<int> imember;
struct iterator {
bool equal (const iterator& other) { return true; }
};
iterator begin () { return iterator{}; }
iterator end () { return iterator{}; }
};
template <template<class> class A, template<class> class B>
bool operator== (const typename basic_thing<A, B>::iterator& lhs, const typename basic_thing<A, B>::iterator& rhs) {
return lhs.equal(rhs);
}
int main ()
{
using Thing = basic_thing<detail::foo, detail::bar>;
Thing t;
cout << typeid(t.fmember).name() << endl;
cout << typeid(t.imember).name() << endl;
bool b = (t.begin() == t.end());
return 0;
}
My goal here is to provide a composable way to define basic_thing::target_type, and this pattern works for that purpose. But, I'm stuck at how to declare operator==() for basic_thing::iterator. Either this isn't very straightforward, or there's something obvious that I'm missing. (Likely the latter.)
g++-7.4.0 with -std=c++11 produces the following:
foo.cc: In function 'int main()':
foo.cc:39:23: error: no match for 'operator==' (operand types are 'basic_thing<detail::foo, detail::bar>::iterator' and 'basic_thing<detail::foo, detail::bar>::iterator')
bool b = (t.begin() == t.end());
~~~~~~~~~~^~~~~~~~~~
foo.cc:27:6: note: candidate: template<template<class> class A, template<class> class B> bool operator==(const typename basic_thing<A, B>::iterator&, const typename basic_thing<A, B>::iterator&)
bool operator== (const typename basic_thing<A, B>::iterator& lhs, const typename basic_thing<A, B>::iterator& rhs) {
^~~~~~~~
foo.cc:27:6: note: template argument deduction/substitution failed:
foo.cc:39:32: note: couldn't deduce template parameter 'template<class> class A'
bool b = (t.begin() == t.end());
^
What are some correct ways to do this? Is it even possible when template templates are involved?
The simpler way is to create it inside the struct directly (as member or friend function):
template <template<class> class A, template<class> class B>
struct basic_thing {
// ...
struct iterator {
bool equal (const iterator& other) { return true; }
bool operator ==(const iterator& rhs) const;
// friend bool operator ==(const iterator& lhs, const iterator& rhs);
};
};
With
template <template<class> class A, template<class> class B>
bool operator== (const typename basic_thing<A, B>::iterator& lhs,
const typename basic_thing<A, B>::iterator& rhs);
A and B are not deducible (on the left of ::).
so only callable the ugly way:
bool b = operator==<detail::foo, detail::bar>(t.begin(), t.begin());
I am trying to do matrix addition using expression templates and for this task I have base class: Exp
template<typename subtype>
class Exp{
public:
inline const subtype& self(void) const{
return *static_cast<const subtype*>(this);
}
};
a derived class: matrix
template<typename T,unsigned rows_,unsigned cols_ >
class matrix : public Exp<matrix<T,rows_,cols_>>{
//some members
};
and another derived class: addExp
template<typename T, typename Op1 , typename Op2>
class addExp: public Exp< addExp<T,Op1,Op2> >{
const Op1& op1;
const Op2& op2;
public:
addExp(const Op1& a, const Op2& b): op1(a), op2(b){}
T& operator()(const std::size_t i,const std::size_t j) const{
return op1(i,j) + op2(i,j);
}
};
I am now trying to do operator overloading on addExp for adding matrices.
template<typename T,typename Lhs, typename Rhs>
inline addExp<T,Lhs, Rhs>
operator+(const Exp<Lhs> &lhs, const Exp<Rhs> &rhs) {
return addExp<T,Lhs, Rhs>(lhs.self(), rhs.self());
}
later in my code I try to put two matrix objects(which should have Exp as base class) as function parameters here but I get an error:
prog.cpp: In function ‘int main()’:
prog.cpp:76:25: error: no match for ‘operator+’ (operand types are ‘matrix<int, 3u, 3u>’ and ‘matrix<int, 3u, 3u>’)
matrix<int,3,3> m3 = m1+m2;
~~^~~
prog.cpp:69:1: note: candidate: template<class T, class Lhs, class Rhs> addExp<T, Lhs, Rhs> operator+(const Exp<Lhs>&, const Exp<Rhs>&)
operator+(const Exp<Lhs> &lhs, const Exp<Rhs> &rhs) {
^~~~~~~~
prog.cpp:69:1: note: template argument deduction/substitution failed:
prog.cpp:76:26: note: couldn't deduce template parameter ‘T’
matrix<int,3,3> m3 = m1+m2;
where did I go wrong here and how do I fix this?
You need to somehow transfer the information of what T is to yout operator+. It can be done in several ways, and what way is best would heavily depends on your use case.
Here is one way of doing it.
template<typename T,unsigned rows_,unsigned cols_ >
class matrix : public Exp<matrix<T,rows_,cols_>>{
using type = T;
//some members
};
template<typename Lhs, typename Rhs, typename T = typename Lhs::type>
inline addExp<T,Lhs, Rhs>
operator+(const Exp<Lhs> &lhs, const Exp<Rhs> &rhs) {
return addExp<T,Lhs, Rhs>(lhs.self(), rhs.self());
}
Suppose I have a small class template as below
template<typename T> class SillyClass {
public:
SillyClass(const T val);
SillyClass(const SillyClass& other);
private:
T data;
};
Now I add the following definitions declarations:
template<typename T> class SillyClass {
public:
SillyClass(const T val);
SillyClass(const SillyClass& other);
SillyClass<T> operator+ (const SillyClass& other);
SillyClass<T> operator+ (const T& val);
private:
T data;
};
and now (after I write the appropriate definitions) I can do things like
SillyClass<int> a(1);
SillyClass<int> b(a);
SillyClass<int> c = a + b;
SillyClass<int> d = a + 3;
So far, so good. However, to be able to write something like
SillyClass<int> e = 3 + a;
I found that must add the following declaration to my class
template<typename T2> friend SillyClass<T2> operator+
(const T2& val, const SillyClass<T2>& other);
so it now reads
template<typename T> class SillyClass {
public:
SillyClass(const T val);
SillyClass(const SillyClass& other);
SillyClass<T> operator+ (const SillyClass& other);
SillyClass<T> operator+ (const T& val);
template<typename TT> SillyClass<TT> friend operator+
(const TT& val, const SillyClass<TT>& other);
private:
T data;
};
I didn't find this in a book and I'd like some help to understand what's happening on this last declaration. For instance, with what is my class being befriended here? Why the additional template declaration? What alternatives do I have in terms of different declarations that lead to the same result (being able to perform 3+a, say)?
Thanks.
with what is my class being befriended here? Why the additional template declaration?
The following expression declared inside your class is a friend declaration:
template<typename TT> SillyClass<TT> friend operator+
(const TT& val, const SillyClass<TT>& other);
The above expression declares your class a friend with a family of overloaded operator+s that take as their left-hand-side parameter a type TT and as their right-hand-side an object SillyClass<TT>. Note though that this is a declaration and not a definition. That is, in order for this to work the template overloaded operator+, must be defined.
What alternatives do I have in terms of different declarations that
lead to the same result (being able to perform 3+a, say)?
For binary operators in order for them to be symmetric must be declared outside the class definition as free functions, and in order to have access to the private members of their class parameters you declare them as a friend function of the respective class.
Based on these lines I would go along with the following implementation:
template<typename T> class SillyClass {
T data;
public:
SillyClass(const T val) : data(val) {}
SillyClass(const SillyClass& other) : data(other.data) {}
template<typename T1, typename T2>
friend SillyClass<typename std::common_type<T1, T2>::type>
operator+(SillyClass<T1> const &lsh, SillyClass<T2>& rhs);
template<typename T1, typename T2>
friend SillyClass<typename std::common_type<T1, T2>::type>
operator+(SillyClass<T1> const &lsh, T2 const &rhs);
template<typename T1, typename T2>
friend SillyClass<typename std::common_type<T1, T2>::type>
operator+(T1 const &rhs, SillyClass<T2> const &rsh);
};
template<typename T1, typename T2>
SillyClass<typename std::common_type<T1, T2>::type>
operator+(SillyClass<T1> const &lhs, SillyClass<T2>& rhs) {
return SillyClass<typename std::common_type<T1, T2>::type>(lhs.data + rhs.data);
}
template<typename T1, typename T2>
SillyClass<typename std::common_type<T1, T2>::type>
operator+(SillyClass<T1> const &lhs, T2 const &rhs) {
return SillyClass<typename std::common_type<T1, T2>::type>(lhs.data + rhs);
}
template<typename T1, typename T2>
SillyClass<typename std::common_type<T1, T2>::type>
operator+(T1 const &lhs, SillyClass<T2> const &rhs) {
return SillyClass<typename std::common_type<T1, T2>::type>(rhs.data + lhs);
}
Live Demo
Instead of only declaring your operator in class, you can define the friend operator inside your class:
SillyClass<T> friend operator+(const T& val, const SillyClass<T>& other)
{
// define it here
}
This way, for each instance of your class, a corresponding friend will be generated. The whole thing works based on something called friend name injection.
Now back to your problem. If you just use an in-class declaration
friend operator+(const T& val, const SillyClass<T>& other);
and then outside your class you define
template<typename T>
friend operator+(const T& val, const SillyClass<T>& other)
you'll get a linker error. Why? Because suppose T=int when you instantiate the class. Then the declaration in your class will read as
friend operator+(const int& val, const SillyClass<int>& other);
and will be a better match than the above template definition whenever you invoke your operator+ on SillyClass<int> and some int. So the linker won't be able to find the definition of the required int instantiation, hence a linker error. On the other hand, the solution I proposed at the beginning of the answer guarantees a corresponding definition for every type, so it will work without any headaches.