D-Programming-Language/phobos — pull request #2735 by MetaLang (2014-11-16 11:48:02+00:00)
Title: Add ApplyConstness template

While experimenting a bit, I realized that there's no easy way to declare a variable with the same constness of another variable, but a different type. You can use typeof, but only if you want the second type/declaration to have the same constness __and__ type as the first. For example:

const(int) i;
//No way to specify that n has the same
//constness as i, but a different type
typeof(i) n;

Unfortunately, you can't assign a bare "const" or "immutable", etc., to an alias, so the only way to store the bare qualifiers is as a string for mixing in. It's not ideal, but there is currently no other way besides the verbose:

static if (typeof(i) == const) const(float) n;
else static if(typeof(i) == immutable) immutable(float) n;
//...

With this PR, that code can be shortened to any of the following:

ApplyConstness(float, i) n; //typeof(n) == const(float)
ApplyConstness(float, typeof(i)) n; //Same
ApplyConstness(float, const(int)) n; //Same

ApplyConstness is quite a long name, but it's the only sufficiently descriptive one I could think of. Suggestions for a better name are welcome.