A user-defined conversion function enables an implicit or explicit conversion between types. Such, a function has the following form (no return type and no parameters):
1 2 3 4 5 6 7 |
struct foo { operator int() const {return 42;} }; foo f; int i = f; // implicit conversion |
1 2 3 4 5 6 7 |
struct foo { explicit operator int() const {return 42;} }; foo f; int i = static_cast<int>(f); // explicit conversion |
Conversion functions must be non-static but can be virtual. However, instead of specifying an explicit type, you can use the auto placeholder to indicate a deduced return type (since C++14). In the following example, the deduced type is int.
1 2 3 4 5 6 7 8 |
struct foo { foo(int const d) : data(d) {} operator auto() {return data;} private: int data; }; |
Conversion functions with deduced return type cannot have a trailing return type and cannot be templetized.
The catch with the deduced type is that if you return a reference, the type that is deduced is not the reference type but the referenced type.
1 2 3 4 5 6 7 8 9 10 |
struct foo { foo(int& d) : data(d) {} operator auto() {return data;} // deduced type is int private: int& data; }; int& r = f; // error: non-const lvalue reference to type 'int' cannot bind to a value of unrelated type 'foo' |
u can use
operator decltype(auto)() {return (data);}
for returning referencesnot a very interesting operator at best. A missed opportunity at worst. https://quuxplusone.github.io/blog/2018/07/12/operator-auto/