User Tools

Site Tools


c:c_overload_by_return_type

C - C++ Overload by Return Type

NOTE: Return types are not considered in overload resolution. The reason is to keep resolution for an individual operator or function call context-independent.

However, this is one approach:

struct func {
    operator string() { return "1";}
    operator int() { return 2; }
};
 
int main( ) {
    int x    = func(); // calls int version
    string y = func(); // calls string version
    double d = func(); // calls int version
    cout << func() << endl; // calls int version
    func(); // calls neither
}

Using Proxy

It's possible, but I'm not sure that it's a technique I'd recommend for beginners. As in other cases, when you want the choice of functions to depend on how the return value is used, you use a proxy; first define functions like getChar and getInt, then a generic get() which returns a Proxy like this:

class Proxy
{
  My const* myOwner;
 
public:
  Proxy( My const* owner ) : myOwner( owner ) {}
  operator int() const
  {
    return myOwner->getInt();
  }
  operator char() const
  {
    return myOwner->getChar();
  }
};

Extend it to as many types as you need.

You do run the risk of introducing ambiguities that wouldn't otherwise be there. In the case of a Proxy, the risk is minor—you're not going to have instances of the Proxy type other than in the case where you want the implicit conversion. Note too that the conversion in the proxy counts as one user defined conversion. If you need std::string, and the proxy only offers operator char const*(), it's not going to work

Using Const

Another approach is that in C++, a function's signature depends partly on whether or not it's const. This means that a class can have two member functions with identical signatures except that one is const and the other is not. If you have a class like this, then the compiler will decide which function to call based on the object you call it on: if it's a const instance of the class, the const version of the function will be called; if the object isn't const, the other version will be called.

This really only makes sense when the member function returns a pointer or a reference to a data member of your class (or a member of a member, or a member of a member of a member, … etc.). Generally returning non-const pointers or references to data members is frowned upon, but sometimes it is reasonable, or simply very convenient (e.g. [] operator). In such cases, you provide a const and a non-const versions of the getter. This way the decision on whether or not the object can be modified rests with the function using it, which has a choice of declaring it const or non-const.

c/c_overload_by_return_type.txt · Last modified: 2020/07/15 10:30 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki