为什么更多主流的静态类型语言不支持返回类型的函数/方法重载?我想不出那样做.通过参数类型支持过载似乎没有那么有用或合理.怎么这么不受欢迎呢?
programming-languages overloading language-design function-calls
我们都知道你可以根据参数重载一个函数:
int mul(int i, int j) { return i*j; }
std::string mul(char c, int n) { return std::string(n, c); }
Run Code Online (Sandbox Code Playgroud)
你能根据返回值重载一个函数吗?根据返回值的使用方式定义一个返回不同内容的函数:
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)
Run Code Online (Sandbox Code Playgroud)
您可以假设第一个参数介于0-9之间,无需验证输入或进行任何错误处理.