Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ return type overload hack

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

like image 682
Anycorn Avatar asked May 12 '10 05:05

Anycorn


People also ask

Can you overload based on return type?

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.

Can we overload method with different return type in C++?

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.

Can you overload method in C?

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).

Can you overload an operator twice?

No this is not possible.


2 Answers

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++.

like image 173
vava Avatar answered Nov 17 '22 00:11

vava


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.

like image 4
Matthew Flaschen Avatar answered Nov 17 '22 01:11

Matthew Flaschen