具有mixin和模板的结构组合 [英] Struct composition with mixin and templates

查看:72
本文介绍了具有mixin和模板的结构组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以组成一个 AB 结构,该结构具有结构 A 的所有成员B

I can compose an AB struct that has all the members of structs A and B:

template AFields() {int a;}
struct A { mixin AFields; }
template BFields() {int b;}
struct B { mixin BFields; }
struct AB { mixin AFields; mixin BFields; }
A a; a.a = 1;
B b; b.b = 2;
AB ab; ab.a = 3; ab.b = 4;

但是,如何构造 AB 我没有控制 A B 的权限,也没有 AFields BFields ?即如何编写 CatStruct 模板,以便编译下面的代码?

But how can I construct AB, if I don't have control over A and B and I don't have AFields and BFields? I.e. how to write the CatStruct template so the code below compiles?

struct A { int a; }
struct B { int b; }
mixin CatStruct!("AB", A, B);
AB ab;
ab.a = 1; ab.b = 2;


推荐答案

这里有很多基础(成员,功能,模板等)。
但是,这里有个入门的提示:

There's a lot of ground to cover here (members, functions, templates, ect.). However, here's an idea to get you started:

import std.typecons;

struct A { int a; }
struct B { int b; }

struct AB
{
  mixin MultiProxy!(A, B);
}

mixin template MultiProxy(A, B) {
  private A _a;
  private B _b;

  mixin Proxy!_a aProxy;
  mixin Proxy!_b bProxy;

  template opDispatch(string op) {
    static if (is(typeof(aProxy.opDispatch!op))) {
      alias opDispatch = aProxy.opDispatch!op;
    }
    else {
      alias opDispatch = bProxy.opDispatch!op;
    }
  }
}

unittest
{
  AB ab;
  ab.a = 4;
  ab.b = 5;

  assert(ab.a == 4);
  assert(ab.b == 5);
}

我没有时间对此进行全面测试,所以我不会如果存在很多问题,我们会感到惊讶(只需查看 Proxy 的实现以了解它必须考虑的所有内容)。

I haven't had time to thoroughly test this, so I wouldn't be suprised if there are a number of areas where it falls over (just look at the implementation of Proxy to see all the things it has to take into account).

但是,通常的想法是创建两个代理,每个代理都明确命名为(aProxy,bProxy),因此我们可以显式调用 opDispatch 取决于哪个编译。

However, the general idea is to create two proxies, each explicitly named (aProxy,bProxy) so we can explicitly call the opDispatch of either one depending on which will compile.

这篇关于具有mixin和模板的结构组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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