Overload a C++ function according to the return va

2019-01-01 15:05发布

We all know that you can overload a function according to the parameters:

int mul(int i, int j) { return i*j; }
std::string mul(char c, int n) { return std::string(n, c); } 

Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used:

int n = mul(6, 3); // n = 18
std::string s = mul(6, 3); // s = "666"
// Note that both invocations take the exact same parameters (same types)

You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.

17条回答
长期被迫恋爱
2楼-- · 2019-01-01 16:01

You cannot overload a function based on the return value only.

However, while strictly speaking this is not an overloaded function, you could return from your function as a result an instance of a class that overloads the conversion operators.

查看更多
春风洒进眼中
3楼-- · 2019-01-01 16:01

You can use the functor solution above. C++ does not support this for functions except for const. You can overload based on const.

查看更多
残风、尘缘若梦
4楼-- · 2019-01-01 16:03

Put it in a different namespace? That would be how I would do it. Not strictly an overload, rather a just having two methods with the same name, but a different scope (hence the :: scope resolution operator).

So stringnamespace::mul and intnamespace::mul. Maybe its not really what you are asking, but it seems like the only way to do it.

查看更多
泪湿衣
5楼-- · 2019-01-01 16:04

As far as I know, you can't (big pity, though...). As a workaround, you can define an 'out' parameter instead, and overload that one.

查看更多
旧时光的记忆
6楼-- · 2019-01-01 16:05

You could use a template, but then you'd have to specify the template parameter when you make the call.

查看更多
登录 后发表回答