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 15:39

No.

You can't overload by return value because the caller can do anything (or nothing) with it. Consider:

mul(1, 2);

The return value is just thrown away, so there's no way it could choose an overload based on return value alone.

查看更多
像晚风撩人
3楼-- · 2019-01-01 15:42

OK you geniuses ;) this is how you do it like a pro.


class mul
{
 int m_i,m_j;
public:
 mull(int i,int j):m_i(i),m_j(j){}
 template
 operator R() 
 {
  return (R)m_i * m_j;
 }
};

use like


double d = mul(1,2);
long l = mul(1,2);

no stupid <>

查看更多
查无此人
4楼-- · 2019-01-01 15:43

You could do something like

template<typename T>
T mul(int i,int j){
    return i * j;
}

template<>
std::string mul(int i,int j){
    return std::string(j,i);
}

And then call it like this:

int x = mul<int>(2,3);
std::string s = mul<std::string>(2,3);

There is no way of overloading on the return value.

查看更多
谁念西风独自凉
5楼-- · 2019-01-01 15:45

Let mul be a class, mul(x, y) its constructor, and overload some casting operators.

查看更多
泛滥B
6楼-- · 2019-01-01 15:47

I presume you could have it return some weird type Foo that just captures the parameters and then Foo has an implicit operator int and operator string, and it would "work", though it wouldn't really be overloading, rather an implicit conversion trick.

查看更多
琉璃瓶的回忆
7楼-- · 2019-01-01 15:47

Short and simple, the answer is NO. In C++ the requirements are:

1: name of functions MUST be the same
2: set of arguments MUST differ
*The return type can be the same or different

//This is not valid
    int foo();
    float foo();

    typedef int Int;

    int foo(int j);
    int foo(Int j);

//Valid:
   int foo(int j);
   char* foo(char * s);
   int foo(int j, int k);
   float foo(int j, float k);
   float foo(float j, float k);
查看更多
登录 后发表回答