此问题基于 Andrei 对 my question on signature constraints. 的回答
struct S(int x, int y) {
void fun(T)(T t) if (is(T U == S!(a, b), int a, int b)) { }
}
template s(int a, int b) {
enum result = S!(a,b)();
alias result s;
}
void main() {
auto s1 = S!(1, 1)();
auto s2 = S!(2, 2)();
auto s3 = s!(3, 3);
auto s4 = s!(4, 4);
s1.fun(s1); // ok
s1.fun(s2); // ok
s1.fun(s3); // compile error
s3.fun(s1); // ok
s3.fun(s3); // compile error
s3.fun(s4); // compile error
}
我不明白为什么代码会产生编译错误。有什么想法吗?
最佳答案
首先,我不建议使用裸模板来生成对象/结构的实例,因为您本质上要求对象是 CTFE 可用的。如果您需要一个实例,您最好的选择是从模板函数中返回
它:
@property S!(a, b) s(int a, int b)()
{
return S!(a, b)();
}
然而,这似乎仍然不适用于模板约束。我认为这必须是一个前端错误。据我所知,似乎无法在 is() 表达式中正确检查返回的类型,除非它已经在其他地方实例化,例如:
struct S(int x, int y)
{
void fun(T)(T t)
if (is(T U == S!(a, b), int a, int b))
{
}
}
@property S!(a, b) s(int a, int b)()
{
return S!(a, b)();
}
void main()
{
auto s1 = S!(1, 1)();
auto s2 = S!(2, 2)(); // comment out and you get errors in fun() call
auto s3 = s!(2, 2);
s1.fun(s3);
}
我会将此作为错误归档。
编辑:归档为Issue 8493 .
关于d - 模板约束内的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11771079/