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
No, and it's not a hack. It's the whole point of operator overloading. As long as your overloads serve a purpose, then why not?
In your example, you allow casts to
int
andfloat
. As long as these two casts perform the same basic logic, i.e.operator int() { return operator float(); }
I see no problem. If they behave differently, this could definitely result in some surprises or ambiguities. This is because I would expect numeric results to have a coherent meaning.Actually it seems you have reinvented a Variant type. Just take a look at all *variant types that are present in many frameworks, eg.: MS uses VARIANT, Qt has QVariant.
The call of the function "function" became kind of context sensitive. I suppose, this trick can be exploited to support subject-oriented programming.
Subject-oriented programming is based on the observation that properties of an object are not inherent to the object itself, but depend on who perceive that object. For example, from the point of view of human, tree is not food, but from the point of view of termite, tree is food. Object-oriented paradigm doesn't support this observation directly, and people often come to complex unnatural designs, because they try to incorporate all different subjective views of an object into one entity ("class"), following thoughtlessly OOP guidelines.
So, let's try to state subjective perceptions explicitly, using the trick in question to get context sensitivity.
Note that the tree doesn't know what eats it.
(great question indeed, made me reflect upon it much)
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.
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
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++.