digitalmars.D - Why isn't opMul allowed in a const expression
- Steven Schveighoffer (23/23) Nov 20 2007 For example:
- Steven Schveighoffer (10/10) Nov 20 2007 I added:
- torhu (5/19) Nov 20 2007 For initializing a constant you need a compile-time value.
- Steven Schveighoffer (14/33) Nov 20 2007 Yep, you are right.
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
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
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
"torhu" wroteSteven Schveighoffer wrote: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? -SteveI 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








"Steven Schveighoffer" <schveiguy yahoo.com>