Search code examples
c++castingc++17

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

Solution

  • 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;
    }