c# - What is wrong with inferred type of template and implicit type conversion? -
i reading "the d programming language" andrei alexandrescu , 1 sentence puzzled me. consider such code (p.138):
t[] find(t)(t[] haystack, t needle) { while (haystack.length > 0 && haystack[0] != needle) { haystack = haystack[1 .. $]; } return haystack; }
and call (p.140):
double[] = [ 1.0, 2.5, 2.0, 3.4 ]; = find(a, 2); // error! ' find(double[], int)' undefined
explanation (paragraph below code):
if squint hard enough, see intent of caller in case have
t = double
, benefit nice implicit conversionint
double
. however, having language attempt combinatorially @ same time implicit conversions , type deduction dicey proposition in general case, d not attempt that.
i puzzled because such language c# tries infer type — if cannot this, user gets error, if can, well, works. c# lives several years , didn't hear story how feature ruined somebody's day.
and questions — dangers involved inferring types in example above?
i can see advantages, easy write generic function , easy call it. otherwise have introduce more parameters in generic class/function , write special constrains expressing allowed conversions sake of inferring types.
the first thing note doesn't there's problem type deduction, it's there's problem type deduction and implicit conversion at same time.
so, if have:
a = find(a, 2.0);
then it's happy deduce double
type.
and if explicitly typed double, it's happy deduce 2
should implicitly cast 2.0
.
what it's not going both @ same time.
now, c# that. , think part agree you, it's convenient , works enough.
it true @ same time can confusing, in cases leads more 1 equally reasonable overload.
why type inference , implicit operator not working in following situations? , why assert.areequal on custom struct implicit conversion operator fail? both questions why particular combination of implicit conversion , type inference didn't work.
unexpected effect of implicit cast on delegate type inference has other factors, again refusing consider method in list of possible matches because argument type didn't match mean problem didn't happen.
they'd both lot simpler if answer "because doing implicit conversion , type inference @ same time, , that's not supported". answer d.
on other hand though, such problems don't arise often, still favour c# design decision allow both, there problems means it's still reasonable design decision not allow them.
Comments
Post a Comment