Inability to dup/~ for const arrays of class objects
Steven Schveighoffer
schveiguy at yahoo.com
Tue May 28 18:31:34 PDT 2013
> I'm implementing sets and the concept is sets of objects not sets of the
> values in the objects. I want to be able to initialize sets using
> arrays and I'm promising that I won't change the array or its contents.
> I'm also trying to promise that I won't (inside the set
> implementation) make any changes to individual objects. But I'm not
> promising that they won't be changed by other code that has access to
> them. The invariant (I wrote) for the sets implies that any changes
> made by that code can't change the sort order of the objects.
Then you are trying to make a *momentary* guarantee.
In essence, you want to transform the array into a set, but still
guarantee that the underlying data hasn't changed.
This is very difficult to express with the type system. The closest you
can get is inout, which *might* be able to do it.
For example:
inout(T)[] copyIt(T)(inout(T)[] arr)
{
// this is quirky, but it's the easiest way to do it without an
equivalent .dup for inout
inout(T)[] result;
result ~= arr;
return result;
}
Now, if you pass in mutable, you get mutable. If you pass in const, you
get const. If you pass in immutable, you get immutable.
I say *might* because I don't know what your code is doing, or how your
set type actually looks. It may be logical, but impossible to currently
express. inout still has some room for improvement (and so does the whole
const system in general).
> No, I really don't want copies although I can see that might have it's
> uses in another application. It's the mathematical concept of sets that
> I'm trying for not just containers. I.e. it's a way of selecting groups
> of objects, combining groups without duplicates, etc.
Another option is to simply define your types as "immutable" types. That
is, specify the data inside is immutable, but the class itself is not.
e.g.:
class C
{
immutable int c;
this(int x) { c = x;}
}
You are hitting a very common pain-point for const/immutable, for which
there is really not a good answer currently.
-Steve
More information about the Digitalmars-d
mailing list