断言失败时如何打印更多?

Arl*_*len 5 d

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];
}
Run Code Online (Sandbox Code Playgroud)

如今,这个断言失败了,我希望看到的实际值rowcol.不幸的是,assert不喜欢writeln或者writefln,所以我做不了类似的事情:

assert(col + row * Col < Row * Col, "index out of bounds. row: %d  col: %d", row, col);
Run Code Online (Sandbox Code Playgroud)

我甚至试过这个:

assert(col + row * Col < Row * Col, "index out of bounds" ~ to!string(row)~ " " ~ to!string(col));
Run Code Online (Sandbox Code Playgroud)

但我不能打电话,to因为它opIndex是纯粹的.我可以暂时删除pureopIndex,但触发因为其他纯方法呼吁索马里发展事务处的长链opIndex.无法调用to也消除了创建我自己的函数传递的可能性assert.

那么,还有什么可以尝试的?我只想在断言失败时打印这些值.

Jon*_*vis 10

目前,如果要转换为pure函数中的字符串或从函数中的字符串转换,您将不得不自己编写转换函数.有些工作已经用于制作类似的功能std.conv.to pure,但我们还没有达到它们的目的.太多的低级构造仍然没有pure,即使它们理论上可能是.正在const为下一个版本的dmd(2.059)制作东西做了很多工作,并且有些工作pure与之相辅相成,因为某些函数Object必须是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));
Run Code Online (Sandbox Code Playgroud)

这将在一个不纯的功能,但直到format可能pure,它将无法在pure一个功能.

现在,你可以将不纯净的东西放在一个debug块中.所以,如果你愿意,你可以做到

debug
{
    assert(col + row * col < row * col,
           format("index out of bounds. row: %d  col: %d", row, col));
}
Run Code Online (Sandbox Code Playgroud)

但是你必须编译-debug或你的断言不会运行.但不管,debug将让你把不纯的代码在你的pure函数用于调试目的,并将于只要编译-debug标志使用,因此它可以作为当前缺乏一个临时的解决方法formatto.