Imcompatible type, const and const

Mike Parker aldacron at gmail.com
Sun Mar 9 19:32:06 PDT 2014


On 3/10/2014 1:15 AM, Duarte wrote:
> Hi guys,
> While I was out there, trying some D and stuff, I came with an error
> message I can't understand.
>
> Let's assume I have something like:
>
> class Point2
> {
>      Vector2 opBinary(string op)(const Point2 _right)
>      {
>          static if(op == "-")
>          {
>              return new Vector2(   this.x - _right.x,
>                                    this.y - _right.y   );
>          }
>      }
>
>      public static float DistanceSq(const Point2 _left, const Point2
> _right)
>      {
>          return _left.DistanceSq(_right);
>      }
>
>      public float Distance(const Point2 _right) const
>      {
>          Vector2 vec = this - _right;
>          [...]
>      }
> }
>
> The line "Vector2 vec = this - _right" is giving me the following error:
> Error: incompatible types for ((this) - (_right)): 'const(Point2)' and
> 'const(Point2)'
>
> What am I missing here? The same code in C++ compile, so I was assuming
> it would just as well compile in D.
>
> Cheers!

I'm assuming that the error is occurring when you call the static 
DistanceSq. What's happening is that the static method takes two const 
Points. The call to _left.DistanceSq means that the this object for that 
call (_left) is const. That call passes because DistanceSq (which I 
assume you've mistyped as Distance here) is declared as a const method. 
The problem, though, is that your opBinary is not a const method so it 
cannot work on const(this) object -- const(this) - const(_right) is what 
you have. If you make opBinary a const method, you won't see this error 
anymore.

Also, it's probably a better idea to use structs for object types like 
vectors and points. D's GC isn't state of the art, so something as 
frequently allocated as points and vectors will likely cause issues.


More information about the Digitalmars-d-ide mailing list