Home > Mobile >  Is it possible to define a custom cast on an object to become the result of a method call?
Is it possible to define a custom cast on an object to become the result of a method call?

Time:05-22

Is it possible to define a custom cast on an object so that the objects casts to the result of a method call?

class Foo {
  public:
    ...
    int method() { return 3; }
};

Foo foo;
int bar = foo   7; // 10

CodePudding user response:

You could provide a conversion function as shown below:

Method 1

Directly return an int without using method inside the conversion function.

class Foo {
  public:
    //conversion function
    operator int()
    {
        return 3;
    }
};

Foo foo;
int bar = foo   7; // bar is initialized with 10

int main()
{
    std::cout<<bar;//prints 10
    return 0;
}

Demo

Or

Method 2

Use method to return an int from inside the conversion function.

class Foo {
  public:
    
    int method() { return 3; }
    
    operator int()
    {
        return method();
    }
};

Foo foo;
int bar = foo   7; // 10

int main()
{
    std::cout<<bar;//prints 10
    return 0;
}

CodePudding user response:

Agh. I was overthinking it.

#include <iostream>
#include <string>

class Foo {
    public:
    Foo() { _data = 3; }
    int method() { return _data; }
    operator int() {
        return method();
    }
    int _data;
};

int main()
{
  Foo foo;
  int bar = foo   7;
  std::cout << bar << std::endl;
}
  • Related