Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overloading operator in different ways depending on template argument

I have a class

template<int n> MyClass<n>

for which I am trying to define the operator &. I want to be able to perform MyClass&MyClass, but also MyClass&MyClass<1> (or MyClass<1>&MyClass would work for me as well) with a different functionality obviously.

template <size_t n>
struct MyClass
{
    //...a lot of stuff
    MyClass<n> operator&(const MyClass<n> &other) const;

    MyClass<n> operator&(const MyClass<1> &other) const;
}

However, I am not able to compile this, as for the case of n being 1 they collide. I tried adding SFINAE, but apparently I don’t understand it well enough to use it in this case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template <size_t n>
struct MyClass
{
    //...a lot of stuff
    MyClass<n> operator&(const MyClass<n> &other) const;

    std::enable_if_t<n != 1, MyClass<n>> operator&(const MyClass<1> &other) const;
}

Does not work for making sure the case of n being 1 doesn’t cause issues. I think it is because SFINAE works for the function template parameters itself, but not the class template parameters.

I believe I could to a specialization of MyClass<1>, but then I would have to replicate all the contents of MyClass<n>. Is there any easy solution to this?

>Solution :

SFINAE only works with templates. You can make the 1st operator& template as:

template <size_t n>
struct MyClass
{
    //...a lot of stuff
    template <size_t x>
    std::enable_if_t<x == n, MyClass<x>> // ensure only MyClass<n> could be used as right operand 
    operator&(const MyClass<x> &other) const;

    // overloading with the template operator&
    // non-template is perferred when MyClass<1> passed
    MyClass<n> operator&(const MyClass<1> &other) const;
};

LIVE

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading