Why can't a method be virtual AND static at the same time?
Steven Schveighoffer
schveiguy at yahoo.com
Thu Jan 30 05:24:09 PST 2014
On Wed, 29 Jan 2014 08:30:53 -0500, Martin Cejp <minexew at gmail.com> wrote:
> This is a feature I've always missed in C++. Consider the code
> below:
>
> import std.stdio;
>
> interface Logger {
> void print(string msg);
> }
>
> class ConsoleLogger : Logger {
> static override void print(string msg) {
> writeln(msg);
> }
> }
>
> void main() {
> Logger logger = new ConsoleLogger;
>
> ConsoleLogger.print("Hello, World!");
> }
>
> Such definition of ConsoleLogger fails to compile. I don't see
> any drawbacks to allowing this though, except the compiler would
> probably have to generate 2 methods internally.
> The way it is now, you have to either define each method twice or
> always create an instance.
> Or am I missing an obvious solution?
Interface Logger {
final void print(string msg) { printImpl(msg); }
void printImpl(string msg);
}
class ConsoleLogger : Logger {
static void print(string msg) {
writeln(msg);
}
override void printImpl(string msg) {
print(msg);
}
}
The issue you have is with the naming, you can't overload a virtual
function with a static one. A static function call is a different call
than a virtual one. You can't mix the two.
-Steve
More information about the Digitalmars-d
mailing list