KentH
KentH

Reputation: 1224

Why is implicit conversion not occurring

Why is my conversion constructor not working? The explicit conversion compiles fine.

struct element {};

struct element_set {
    element_set(const element& e) : e(e) {};
    element_set& operator+(const element& e) { return *this; }

    const element &e;
};

element e1, e2;

auto es1 = element_set(e1) + e2; 
auto es2 = e1 + e2;

kent:kas kent$ g++ -std=c++14 -g implicit.cc
implicit.cc:13:15: error: invalid operands to binary expression ('element' and 'element')
auto es2 = e1 + e2;
           ~~ ^ ~~
1 error generated.

Based on the answer from @Krizz and comment from @BenVoigt below, I can get implicit conversion working by adding a friend to element_set:

struct element_set {
    element_set(const element& e) : e(e) {};
    element_set& operator+(const element& e) { return *this; }
    friend element_set operator+(const element& l, const element& r);
    const element &e;
};

element_set operator+(const element& l, const element& r) { return l+r; }

Thanks for the quick help!

Upvotes: 0

Views: 65

Answers (1)

Krizz
Krizz

Reputation: 11542

Your code, where you use operators, is equivalent to:

element e1, e2;
auto es1 = element_set(e1).operator+(e2); 
auto es2 = e1.operator+(e2);

Can you see now why this does not work? There is no method operator+ on struct element. So, the only thing compilator can try are reachable functions of form:

R operator+(TypeConvertibleFromElement, TypeConvertibleFromElement)

No such a function exists.

Note: The above is for explanatory purposes only. Discussing the C++ language specification and how compilers work would require a little bit more precise descriptions.

Upvotes: 2

Related Questions