I've been working on my project and expected weird behavior when using opCall with structs. I've made a simple test case to demonstrate it. Following code compiles on DMD 2.057:
import std.stdio;
import std.stdio;
void main()
{
auto test = Test("");
auto nested = Test("1");
nested.tests ~= Test("2");
test.tests ~= nested;
writeln(test.get("1"));
writeln(test.opCall("1"));
writeln(test("1"));
}
struct Test
{
Test[] tests;
string str;
public this(string str)
{
this.str = str;
}
public ref Test get(string str)
{
return tests[0];
}
alias get opCall;
}
Current result:
Test([Test([], "2")], "1")
Test([Test([], "2")], "1")
Test([], "1")
Expected result:
Test([Test([], "2")], "1")
Test([Test([], "2")], "1")
Test([Test([], "2")], "1")
As you may see, `test.opCall` works correct, when `test()` is not.
Comment #1 by gasper.azman — 2012-05-08T10:37:12Z
This is more about opCall not working for structs whenever a constructor is present. For instance, this works:
import std.stdio;
struct B {
int number;
string word;
static B opCall(int n) {
B b = {n, ""};
return b;
}
string opCall(string w)
{
word = w;
return word;
}
}
void main() {
auto b = B(3);
writeln(b("Hello World"));
}
but this doesn't:
import std.stdio;
struct A {
int number;
string word;
this(int n) {
number = n;
word = "";
}
string opCall(string w)
{
word = w;
return word;
}
}
int main() {
auto a = A(3);
writeln(a("Hello World"));
}
atom@kamichan $ dmd test.d
test.d(20): Error: constructor test.A.this (int n) is not callable using argument types (string)
test.d(20): Error: cannot implicitly convert expression ("Hello World") of type string to int
test.d(18): Error: function D main has no return statement, but is expected to return a value of type int
atom@kamichan $ dmd
DMD64 D Compiler v2.059
Comment #2 by andrej.mitrovich — 2012-09-17T10:49:44Z
*** Issue 8677 has been marked as a duplicate of this issue. ***
Comment #3 by bearophile_hugs — 2012-10-06T11:03:06Z
Seems fixed. See Issue 6036
Comment #4 by k.hara.pg — 2012-10-06T16:44:29Z
*** This issue has been marked as a duplicate of issue 6036 ***