59

Little-known C++: operator auto

 5 years ago
source link: https://www.tuicool.com/articles/hit/EjAfAnj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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'

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK