相同模板参数时不同类型?
struct Matrix(T, size_t row, size_t col){
alias row Row;
alias col Col;
auto opBinary(string op, M)(in M m) const if(op == "*"){
static assert(Col == M.Row, "Cannot Mix Matrices Of Different Sizes.");
// whatever...
return Matrix!(T, Row, M.Col)();
}
}
void main(){
Matrix!(double, 2, 3) m1 = Matrix!(double, 2, 3)();
Matrix!(double, 3, 2) m2 = Matrix!(double, 3, 2)();
Matrix!(double, 2, 2) m3 = m1 * m2; // ERROR
// Error: cannot implicitly convert expression (m1.opBinary(m2)) of type Matrix!(double,row,col) to Matrix!(double,2,2)
}
为什么会出现错误以及如何解决这个问题?
struct Matrix(T, size_t row, size_t col){
alias row Row;
alias col Col;
auto opBinary(string op, M)(in M m) const if(op == "*"){
static assert(Col == M.Row, "Cannot Mix Matrices Of Different Sizes.");
// whatever...
return Matrix!(T, Row, M.Col)();
}
}
void main(){
Matrix!(double, 2, 3) m1 = Matrix!(double, 2, 3)();
Matrix!(double, 3, 2) m2 = Matrix!(double, 3, 2)();
Matrix!(double, 2, 2) m3 = m1 * m2; // ERROR
// Error: cannot implicitly convert expression (m1.opBinary(m2)) of type Matrix!(double,row,col) to Matrix!(double,2,2)
}
Why the error and how can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,目前模板是使用其参数类型而不是参数类型来实例化的。
如果您将 return 语句更改为:
它将编译,因为它是用
int
实例化的,而不是size_t
(它是 uint 或 ulong)。这是一个长期存在的错误,尽管他以前不喜欢它,沃尔特最近改变了他的请注意支持更改此设置以使用参数类型。 这里是解决此问题的拉取请求(它将在下一个DMD 版本),链接各种相关错误。
The problem is that, currently, templates are instantiated with their argument types, not their parameter types.
If you changed your return statement to:
It will compile, because it was instantiated with
int
, notsize_t
(which is uint or ulong).This is a long-standing bug and although he previously didn't like it, Walter recently changed his mind supporting changing this to use the parameter types. Here is the pull request fixing this issue (it will be in the next DMD release), linking various related bugs.