模板约束内的模式匹配 [英] Pattern-matching inside a template constraint

查看:57
本文介绍了模板约束内的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该问题基于安德烈(Andrei)对我对签名约束的问题的回答。

This question is based on Andrei's answer to 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
}

我不明白为什么代码会产生编译错误。有想法吗?

I don't understand why the code is producing compile errors. Any ideas?

推荐答案

首先,我不建议使用裸模板来生成对象/结构的实例,因为您本质上要求对象是可CTFE的。如果需要实例,最好的选择是从模板化函数中返回

First, I wouldn't recommend using a naked template to generate an instance of an object/struct, because you're essentially requiring the object to be CTFE-able. If you need an instance your best option is to return it from a templated function:

@property S!(a, b) s(int a, int b)()
{
    return S!(a, b)();
}

但是,这似乎仍然无法与模板约束一起使用。我认为这必须是前端错误。据我所知,似乎返回的类型不能在is()表达式中正确检查,除非它已在其他地方实例化,例如:

However this still doesn't seem to work with the template constraint. I think this has to be a front-end bug. From what I can tell it seems that the type returned cannot be properly checked in the is() expression unless it was already instantiated somewhere else, e.g.:

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);
}

我将其记录为错误。

编辑:归档为问题8493

这篇关于模板约束内的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆