Little-known C++: operator auto

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):

struct foo
{
   operator int() const {return 42;}
};

foo f;
int i = f;  // implicit conversion

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.

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.

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'

2 Replies to “Little-known C++: operator auto”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.