C++ return type overload hack

2020-05-23 07:19发布

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

7条回答
再贱就再见
2楼-- · 2020-05-23 07:48

If you really mean something like this:

 1 struct proxy {
 2     operator long() { return refs.first; } // long has greater precision
 3     operator double() { return refs.second; } // double has greater range
 4     proxy( long const &, double const & );
 5     pair< long const &, double const & > refs;
 6 };
 7
 8 proxy function() {
 9     return proxy( numeric_limits<long>::max() + 1,
                     double( numeric_limits<long>::max() ) );
10 }
11 int v = function(...);
12 double u = function(...);

Then yes, I think that's cool and I would count it as a hack.

If it works. I didn't test it at all.

查看更多
登录 后发表回答