www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - opCall with struct alias this

reply Patric Dexheimer <patric.dexheimer gmail.com> writes:
struct Base(T){
	static T opCall(Args...)( Args args ){
		writeln(args);
		writeln("opCall");
		T t;
		return t;
	}
}

struct Data{
	Base!Data b;
	alias b this;
}

void main()
{	
         // Expected: opCall of Base!Data, but get error
	// auto x = Data(10);
         // opCall called. What just happened here?
         // never saw anything about init as function.
	auto y = Data.init(10);
}
May 05
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Friday, 5 May 2017 at 13:05:35 UTC, Patric Dexheimer wrote:
 	static T opCall(Args...)( Args args ){
You should never use static opCall. They are ambiguous with non-static opCall as well as with constructors. It is a buggy mess that should never have been in the language in the first place.
         // Expected: opCall of Base!Data, but get error
 	// auto x = Data(10);
         // opCall called. What just happened here?
It is ambiguous with a constructor call on Data. It is trying to construct a Data, but there's not applicable constructor so it is an error. Note that alias this NEVER applies to constructors (and since static opCall is ambiguous with constructors, that doesn't work either), but only works on existing objects.
         // never saw anything about init as function.
 	auto y = Data.init(10);
T.init is an existing value used to initialize any type, so it is no longer a constructor and can call operator overloads.... But, while this should be a non-static opCall, static opCall will hijack that too. Your short code hit the two big reasons why static opCall ought to be deprecated and totally removed: it gets confused for ctors and non-static opCalls, breaking in situations where you think it would be them, and cannot coexist with them either. I suggest you find some other way entirely to write the code.
May 05
parent Patric Dexheimer <patric.dexheimer gmail.com> writes:
On Friday, 5 May 2017 at 13:19:03 UTC, Adam D. Ruppe wrote:
 On Friday, 5 May 2017 at 13:05:35 UTC, Patric Dexheimer wrote:
 [...]
You should never use static opCall. They are ambiguous with non-static opCall as well as with constructors. It is a buggy mess that should never have been in the language in the first place. [...]
It make sense. Even liking of the possibilities of static opCall. But I believe that somethings must exist to evade opCall usages now like empty params ctor on structs.
May 05