mercredi 22 juillet 2020

ADL and friend functions of templated types

I am attempting to use templates to automatically generate a large number of operators for me. They are very similar to the following code, which does not compile:

struct A
{
    int value = 1;
};

struct B
{
    int value = 2;
};  

template<typename ParamA, typename ParamB>
struct C
{
    C(int v) : value(v) {}
    
    friend C operator+(const ParamA& a, const ParamB& b)
    {
        return C(a.value + b.value);
    }
    
    int value;
};

int main()
{
    C<A, B> c = A() + B();
}

Error:

 In function 'int main()':
26:21: error: no match for 'operator+' (operand types are 'A' and 'B')
26:13: warning: unused variable 'c' [-Wunused-variable]

Why can't Argument Dependent Lookup find the operator+ for A and B? I think it might be because it's neither in the global namespace, nor the same namespace as A or B, but I'm not sure how to fix that.

Does anybody know if what I'm attempting to do here can work?

Aucun commentaire:

Enregistrer un commentaire