| |
| Posted by Biotronic in reply to Tony | PermalinkReply |
|
Biotronic
| On Wednesday, 15 November 2017 at 08:43:01 UTC, Tony wrote:
> Error: function test_warnings.MyClass.SomeMethod has no return statement, but is expected to return a value of type int
>
> but if I make it a template class:
>
> class MyClass(T) {
>
> there is no compile error. I don't know why the error isn't given for the template code as well.
As Andrea points out, it's because it's a template. There are reasons for this that may not be immediately obvious, though. Static if is one:
class Foo(T) {
int bar() {
static if (is(T == int)) {
return 0;
} else static if (is(T == string)) {
return 1;
}
}
}
In the general case, bar() would be missing a return statement. However, if the only uses are when T is either a string or an int, that's no problem, since the failure case doesn't see use.
Another example is mixins:
class Foo(string s) {
int bar() {
mixin(s);
}
}
The compiler now has absolutely no idea what bar() might or might not return, until s is specified. If s is "return 3;", everything's hunky-dory. If it's "return string.init;", bar will fail to compile. It's reasonable for the type to only accept correct code, so this is a non-problem in practice.
Next up, overloads:
class Foo(T) {
int bar() {
return baz(T.init);
}
}
int baz(int n) {
return n;
}
void baz(string s) {}
Members of the template argument:
class Foo(T) {
int bar() {
T.baz();
}
}
There's plenty other cases where the compiler simply cannot tell if the code is invalid without instantiating the template, and where it's valid in some cases but not others. There are other languages that require the equivalent of template parameters to conform to some defined meta-type, and there are benefits to both sides of that discussion. D has chosen to go the loosely (or duck-) typed way, and I feel it's a good match for the rest of the language.
--
Biotronic
|