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

Martin Cejp minexew at gmail.com
Wed Jan 29 06:24:10 PST 2014


On Wednesday, 29 January 2014 at 13:39:24 UTC, Vladimir Panteleev 
wrote:
> 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?
>

Oh no, these are supposed to be 2 independent usage examples, 1) 
being able to pass an instance of ConsoleLogger to a 
function/class expecting Logger and 2) being able to call a 
method without any instance at all.

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

At compile time? Wow. Well, I guess this might work for me then 
:) (though there's no way around having to use 2 different names 
for the class and the const instance, is there?)


More information about the Digitalmars-d mailing list