Edmund's blog

Writing code.

Overload by return type

In C++ it is possible to have two functions with the same name, as long as the arguments are different. This is called overloading.

1
2
void GetValue(std::string& str);
void GetValue(bool& flag);

But how about overloading by return type? Say that we want to be able to write the following code.

1
2
3
4
Test test("true");

std::string str = test.Value();
bool flag = test.Value();

Is that possible? Well, not directly. The language does not allow overloading by return type.

1
2
std::string Value();
bool Value();  // does not compile

The trick is to use a proxy class and then implement conversion operators.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Test
{
public:
    Test(const std::string& str) : m_str(str) {}

    std::string GetString() const { return m_str; }
    bool GetBool() const { return m_str == "true"; }

    class Proxy
    {
    public:
        Proxy(const Test* pObj) : m_pObj(pObj) {}

        // Conversion operators
        operator std::string() const { return m_pObj->GetString(); }
        operator bool() const { return m_pObj->GetBool(); }

    private:
        const Test* m_pObj;
    };

    Proxy Value() const { return Proxy(this); }

private:
    std::string m_str;
};

There is only one Value() function. It returns a proxy object. The proxy class implements one conversion operator for each return type. It all just works.