Search code examples
c++c++11templatesoperator-overloadingtemplate-meta-programming

Overload operator for different template parameters


#include <cstddef>

template <typename T, std::size_t MaxElements>
struct circular_buffer{};

template <typename circular_buffer>
bool operator==(const circular_buffer &a, const circular_buffer &b) {
    return true;
}

int main() {
    circular_buffer<int, 2> a;
    circular_buffer<int, 3> b;
    a == b;
    return 0;
}

This code is work only for 2==3. But my 2 != my 3. Help me to repair operator.


Solution

  • Following might work for you:

    template <typename T, std::size_t M1, std::size_t M2>
    bool operator==(circular_buffer<T, M1> const & a, circular_buffer<T, M2> const & b) {
        // some meaningful logic
        return true;
    };
    

    Problem you have is that a and b are of different types, i.e. those two objects have different MaxElements template parameter. Thus, you need to provide operator == overload that will handle this case.