0

I wonder why this code does not compile:

struct S{ int m; };

template<class T, class = std::enable_if_t<std::is_same_v<T, S>>>
T& operator+=(T&& arg0, int arg1)
{
    arg0.m += arg1;
    return arg0;
}

int main()
{   
    S val0{ 0 }; int val1{ 1 };
    val0 += val1;

    return 0;
}

But it does compile either when SFINAE removed or when basic integer is used instead of a struct (with an appropriate template code change).

1 Answer 1

1

The issue here is that for forwarding references, since val0 is an lvalue, T gets deduced as a S&, not a S. That causes std::is_same_v<T, S> to fail as a S is not the same as a S&. To fix this you can use std::decay_t to remove the reference like

template<class T, std::enable_if_t<std::is_same_v<std::decay_t<T>, S>, int> = 0>
T& operator+=(T&& arg0, int arg1)
{
    arg0.m += arg1;
    return arg0;
}

I also adjusted the template to use a defaulted non-type parameter instead of defaulted type parameter. Doing it this way allows you to overload the function easier as default type arguments are not part of the function signature unlike default values.

3
  • @oleksijp I'd have to see the code you are using in order to tell you. If you changed T&& to int&& then I can tell you, you no longer have a forwarding reference, but an rvalue reference. Feb 15, 2021 at 17:37
  • I think maybe it's because there is a non-template overload for ints :D
    – Oleksa
    Feb 15, 2021 at 17:42
  • @oleksijp Ah yes, int& operator +=(int, int) is already defined by the compiler. Feb 15, 2021 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.