Why can't a method be virtual AND static at the same time?

Vladimir Panteleev vladimir at thecybershadow.net
Wed Jan 29 05:39:23 PST 2014


On Wednesday, 29 January 2014 at 13:30:54 UTC, Martin Cejp 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!");
> }

I don't understand this code. You have a "logger" local variable, 
but don't use it. Do you want the compiler to autodetect which 
local variable to use by selecting one in the current scope?

> 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?

What are you trying to accomplish?

You can use object instances as namespaces, too. Example:

/////////////////////////////////////////////////////////
import std.stdio;

interface Logger
{
	void print(string msg);
}

class ConsoleLoggerImpl : Logger
{
	override void print(string msg) const
	{
		writeln(msg);
	}
}

const ConsoleLogger = new ConsoleLoggerImpl;

void main()
{
	ConsoleLogger.print("Hello, World!");
}
/////////////////////////////////////////////////////////

Note that ConsoleLogger is "instantiated" at compile time, not 
runtime. To instantiate it at runtime, during initialization, you 
can use a static constructor.


More information about the Digitalmars-d mailing list