www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Why isn't opMul allowed in a const expression

reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
For example:
struct X
{
  int value;
  X opMul(int y)
  {
    return X(y * value);
  }
}

void main()
{
  const X myX = X(4); // OK
  const X myX2 = X(4 * myX.value); // OK
  const X myX3 = myX * 4; // Error
}

On dmd 1.023 I get:
Error: non-constant expression ((X(4)).opMul)(4)

On dmd 2.006, after adding a const qualifier to opMul, I get:
Error: non-constant expression cast(const X)((X(4)).opMul)(4)

This is somewhat discouraging, as I cannot use my nifty operator overloads 
to generate constant value type structs.

Is this a bug?

-Steve 
Nov 20 2007
parent reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
I added:

  static X tmpOpMul(X x, int y)
  {
    return X(x.value * y);
  }

To X, and I can do:

static myX4 = X.tmpOpMul(myX, 4);

without error.  I don't see how this is any different than calling opMul. 
It should be evaluatable at compile time, no?

-Steve 
Nov 20 2007
parent reply torhu <no spam.invalid> writes:
Steven Schveighoffer wrote:
 I added:
 
   static X tmpOpMul(X x, int y)
   {
     return X(x.value * y);
   }
 
 To X, and I can do:
 
 static myX4 = X.tmpOpMul(myX, 4);
 
 without error.  I don't see how this is any different than calling opMul. 
 It should be evaluatable at compile time, no?
 
For initializing a constant you need a compile-time value. From the docs about compile-time functions: "4. the function may not be a non-static member, i.e. it may not have a this pointer"
Nov 20 2007
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
"torhu" wrote
 Steven Schveighoffer wrote:
 I added:

   static X tmpOpMul(X x, int y)
   {
     return X(x.value * y);
   }

 To X, and I can do:

 static myX4 = X.tmpOpMul(myX, 4);

 without error.  I don't see how this is any different than calling opMul. 
 It should be evaluatable at compile time, no?
For initializing a constant you need a compile-time value. From the docs about compile-time functions: "4. the function may not be a non-static member, i.e. it may not have a this pointer"
Yep, you are right. There needs to be a change here. Either: 1. I need to be able to specify opX as a static function, where opX is a binary math operator. 2. I need to be able to use struct member functions as long as they adhere to the other rules of CTFE. I don't think this request is unreasonable. Structs are different from classes in that all member functions are final. So there is no question as to calling a virtual method, or how to construct a struct object to call the method with. Without something of this nature, I can't create a true value type. Walter, is something like this being planned? -Steve
Nov 20 2007