www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Small opCall problem

reply bearophile <bearophileHUGS lycos.com> writes:
This is a small C++ program that compiles:

template<typename T> struct Foo {
    Foo(T x) {}
    template<typename U> void operator()(U y) {}
};
int main() {
    Foo<int> foo(1);
    foo(1.5);
}


I think this is an equivalent D2 program:

struct Foo(T) {
    this(T x) {}
    void opCall(U)(U y) {}
}
void main() {
    auto foo = Foo!int(1);
    foo(1.5);
}


But dmd 2.046 prints:
temp.d(7): Error: constructor temp.Foo!(int).Foo.this (int x) is not callable
using argument types (double)
temp.d(7): Error: cannot implicitly convert expression (1.5) of type double to
int

Is this a bug in my D code? If it's a bug in my D code, do you know how to
translate that C++ code in D2?

Bye and thank you,
bearophile
May 30 2010
next sibling parent Philippe Sigaud <philippe.sigaud gmail.com> writes:
On Sun, May 30, 2010 at 17:04, bearophile <bearophileHUGS lycos.com> wrote:

 struct Foo(T) {
    this(T x) {}
    void opCall(U)(U y) {}
 }
 void main() {
    auto foo = Foo!int(1);
    foo(1.5);
 }
I've had this one too. I think it's a bug, because foo is already constructed when foo(1.5) is used. So the compiler should know it's an opCall and not a constructor call. The only solution I found was a kludge: struct Foo(T) { void initialize(T)(T x) {} // in my case, their was some data initialization there. void opCall(U)(U y) {} } Foo!T foo(T)() { Foo!T f; f.initialize(); return f;} void main() { auto f = foo(1); f(1.5); } Philippe
May 30 2010
prev sibling parent reply BCS <none anon.com> writes:
Hello bearophile,

 struct Foo(T) {
 this(T x) {}
 void opCall(U)(U y) {}
 }
 void main() {
 auto foo = Foo!int(1);
 foo(1.5);
 }
FWIW, The struct being a template is extraneous.
 temp.d(7): Error: constructor temp.Foo!(int).Foo.this (int x) is not callable 
using argument types (double) The lookup seems to think you are calling the constructor. Should make it easy to find the bug. (And yes, I think this is a bug) -- ... <IXOYE><
May 30 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
BCS:
 FWIW, The struct being a template is extraneous.
You are right, thank you. I have added the simplified example: http://d.puremagic.com/issues/show_bug.cgi?id=4253 Bye, bearophile
May 30 2010
parent Philippe Sigaud <philippe.sigaud gmail.com> writes:
On Sun, May 30, 2010 at 18:31, bearophile <bearophileHUGS lycos.com> wrote:

 BCS:
 FWIW, The struct being a template is extraneous.
You are right, thank you. I have added the simplified example: http://d.puremagic.com/issues/show_bug.cgi?id=4253
This one had me gnashing my teeth. I voted it up. Philippe
May 30 2010