I was bored and came up with such hack (pseudocode):
1 struct proxy {
2 operator int(); // int function
3 operator double(); // double function
4 proxy(arguments);
5 arguments &arguments_;
6 };
7
8 proxy function(arguments &args) {
9 return proxy(args);
10 }
11 int v = function(...);
12 double u = function(...);
is it evil to use in real code?
my possible usage scenario is for example product of array elements, which may/may not overflow:
int size(short *array);
short size(short *array);
The reason for function, in case you use templates, than template parameters can be inferred from function arguments
The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here.
You cannot overload function declarations that differ only by return type. The function overloading is basically the compile time polymorphism. It checks the function signature. If the signatures are not same, then they can be overloaded.
This feature is present in most of the Object Oriented Languages such as C++ and Java. But C doesn't support this feature not because of OOP, but rather because the compiler doesn't support it (except you can use _Generic).
No this is not possible.
I'd rather use template specialization, just feels less "hacky" and probably will be faster (no object creation, although of course that can be optimized away by smart compiler).
But anyway, I'd rather see code like
template<typename T> T function();
template<> int function() {
return 1;
}
template<> float function() {
return 1.0;
}
....
int a = function<int>();
float b = function<float>();
Nothing wrong with your code though, especially if you stay away from numeric types/pointers since otherwise unanticipated effects might occur, rules of conversion is quite complicated in C++.
The issue is that if the function has two return types, it's probably doing two different (alternative) things . And to the extent possible, each function/method should do one coherent thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With