如何使用类型推断删除变量声明中的不可变/不可变?有可能吗?
immutable uint immutableX = 42;
// keep the type (uint) but remove the immutability
/* compiler magic */ mutableX = immutableX;非类型推理解决方案是:
uint mutableX = immutableX;一个完整的例子:
void main()
{
immutable uint immutableX = 42;
pragma(msg, "immutableX: ", typeof(immutableX));
assert(typeof(immutableX).stringof == "immutable(uint)");
// how to use type inference so that possible immutable/const is removed ?
// the expected type of mutableX is uint
auto mutableX = immutableX;
pragma(msg, "mutableX: ", typeof(immutableX));
// this should be true
assert(typeof(immutableX).stringof == "uint");
}发布于 2019-03-15 07:06:36
根据用例的不同,有std.traits.Unqual,它移除最外层的immutable、const、shared等:
import std.traits : Unqual;
immutable int a = 3;
Unqual!(typeof(a)) b = a;
static assert(is(typeof(b) == int));一个更简单的解决方案可能是cast()
immutable int a = 3;
auto b = cast()a;
static assert(is(typeof(b) == int));哪个是正确的取决于你将在哪里和如何使用它。
https://stackoverflow.com/questions/55176071
复制相似问题