d - 模板约束内的模式匹配

标签 d

此问题基于 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/

相关文章:

eclipse - 滴滴涕错误 : D Standard Library [Error: none found]

linker-errors - GDC D2编译:未定义对_Unwind_SjLj_XYZ的引用

Luad 使用独立的 Lua

转换帮助 : __asm__ __volatile__

d - D 语言中结构体和类之间的使用偏好

d - 如何从 char[] 中删除元素?

d - 如何删除关联数组中最近最少访问的键?

d - 'setMaxMailboxSize' 的奇怪行为

sockets - D套接字编程基本连接脚本

d - 如何在 D 2.0 中使用 wchar** 初始化 wstring[]