Real opIndex(size_t row, size_t col = 0) const pure nothrow {
assert(col + row * Col < Row * Col, "index out of bounds.");
return _data[col + row * Col];
}
今天这个断言失败了,我希望看到row
和col
的实际值。不幸的是,assert
并不像writeln
或writefln
,所以我无法做到:
assert(col + row * Col < Row * Col, "index out of bounds. row: %d col: %d", row, col);
我甚至试过这个:
assert(col + row * Col < Row * Col, "index out of bounds" ~ to!string(row)~ " " ~ to!string(col));
但我无法致电to
,因为opIndex
是纯粹的。我可以暂时从pure
删除opIndex
,但这会触发一长串的撤消操作,因为其他纯方法正在调用opIndex
。无法调用to
也无法创建我自己的函数以传递给assert
。
那么,还有什么可以尝试的?我只想在断言失败时打印这些值。
答案 0 :(得分:10)
目前,如果您想要转换为pure
函数中的字符串或来自字符串,您必须自己编写转换函数。有些工作已经用于制作std.conv.to
pure
之类的功能,但我们还没有达到它们的目的。太多的低级构造仍然不是pure
,即使它们理论上可能也是如此。很多工作正在制作const
- 正确的下一个版本的dmd(2.059),而pure
的一些工作与之相辅相成,因为Object
中的某些函数{1}}必须是pure
,const
,@safe
和nothrow
。因此,std.conv.to
很有可能pure
能够assert(col + row * col < row * col,
format("index out of bounds. row: %d col: %d", row, col));
与下一版本的字符串进行转换。即使它不会在下一个版本中发生,它很快就会发生,因为它确实需要发生(正如你的困境所示)。但在那之前,你自己就是这样。
假设所有这些都已整理出来,那么为断言创建字符串的最佳方法是
format
这将在不纯的函数中起作用,但在pure
可以pure
之前,它不会在debug
函数中工作。
现在,您可以将不纯的内容放入debug
{
assert(col + row * col < row * col,
format("index out of bounds. row: %d col: %d", row, col));
}
块中。所以,如果你愿意,你可以做到
-debug
但是您必须使用debug
进行编译,否则您的断言将无法运行。但无论如何,pure
将允许您将不纯的代码放在您的-debug
函数中以进行调试,并且只要使用format
标志就会编译,因此它可以作为针对当前to
和{{1}}缺陷的临时解决方法。