Derived class and operators

Hi all, I have the following problem:
I need to define the operator+() in the base class and the operator^(const derived &) in the derived class.
The code is as follow:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>

template<class Typ>
class base{
public:
	const base<Typ> operator+() const{
		base<Typ> result;
		result.fElement = +fElement;
		return result;
	}
protected:
	Typ fElement;
};

class derived : public base<double>{
public:
	const derived operator^(const derived & rgh) const{
		std::cout << fElement << " ^ " << rgh.fElement << std::endl;
	};
};

int main(){
	derived a, b;
	+a;		// It compiles
	a^b;		// It compiles
	//+a^b;		// It doesn't compile
	+(a^b);		// It compiles
	return 0;

If I de-comment the line in the main() it complains.

error: no match for 'operator^' in 'a.derived::<anonymous>.base<Typ>::operator+ [with Typ = double]() ^ b'

Why?
Thank you for helping,

Fil
Last edited on
The compiler is saying that there is no operator^ that takes a base<double> (result of operator+) on the left and a derived on the right.

You could fix that by adding a derived-returning operator+ to the derived class, but this whole design seems strange: what kind of relationship do these classes have? Are you really planning polymorphic behavior based on run-time decisions?

If all you're trying to do is to give your base<double> a special member function that other base<T> don't have, then specialize:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <type_traits>

template<class Typ>
class base {
public:
    const base<Typ> operator+() const{
        base<Typ> result;
        result.fElement = +fElement;
        return result;
    }

    template<typename T>
    typename std::enable_if<std::is_same<T, base<double>>::value,
    const base<double>>::type
    operator^(const T& rgh) const
    {
        std::cout << fElement << " ^ " << rgh.fElement << '\n';
        return *this;
    }
private:
    Typ fElement;
};

typedef base<double> derived;

int main(){
    derived a, b;
    +a;     // It compiles
    a^b;        // It compiles
    +a^b;       // It compiles
    +(a^b);     // It compiles

    base<int> c;
    +c; // It compiles
//     c^c; // no ^ for base<int>
}


demo: http://ideone.com/85EUW0
Last edited on
Topic archived. No new replies allowed.