C++Guns – RoboBlog blogging the bot

26.07.2024

C++ Guns: Overloading friend operator for class template - the right way

Filed under: Allgemein — Tags: — Thomas @ 14:07

Goal

Overload operator +=, << etc. as free function for a templated class with private member variables without boilerplate code.
Choose free function to achieve less coupling than with member functions.
In the example you can imagine the Type as Array2D for a use case.

Solution

template<typename T>
class Type {
public:
    // free function form of the operator
    // no repeat of the template parameters for class Type necessary
    // with the friend keyword this is still a free function but can 
    // access private variables like a member function
    friend Type& operator+=(Type& lhs, double value) {
        lhs.data += value; // can access private member variable
        return x;
    }

private:
    double data = 0;
};


void f(Type<double>& x) {
    x += 2.0;
}

Not a Solution

// forward declaration, not usual
template<typename T>
class Type;

// Definition of the function is placed bevor the definition of the type. 
// This is also not usual but needed for the friend declaration later in the code.
// Repeat of the template parameter.
template<typename T>
inline Type<T>& operator+=(Type<T>& lhs, double value) {
    lhs.data += value;    
    return lhs;
}

template<typename T>
class Type {

private:
    double data = 0;

    // templated friend declaration. watch the necessary but very unusual <> here.    
    friend Type& operator+= <>(Type& lhs, double value);
};

void f(Type<double>& x) {
    x += 2.0;
}

C.4: Make a function a member only if it needs direct access to the representation of a class https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-member
Sources: https://stackoverflow.com/questions/4660123/overloading-friend-operator-for-class-template

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress