variadic mixin templates and other stuff

Martin Drasar drasar at ics.muni.cz
Fri Apr 20 06:23:10 PDT 2012


Hi,

I am migrating a C++ project to D and I have hit a roadblock that I hope
you might help me with.

My code is heavily inspired by the COM architecture, so I have naturally
take a look at std/c/windows/com.d, just to find out that it does not
contain all I need.

In the C++ code I have several interfaces and a class. The class
inherits from these interfaces, exposes some of them and it is possible
to get one interface from another using the QueryInterface function by
supplying correct GUID:

class C : IA, IB, IC
{
  EXPOSE_INTERFACE(IA, IC);
  ...
}

where EXPOSE_INTERFACE is macro that expands to something like this:

void QueryInterface (IComponent** comp, GUID* guid)
{
  ...
  if (guid == IAGuid) *comp = ...some casting
  if (guid == IBGuid) *comp = ...some casting
  ...
}

So I was thinking that in D I could use mixin templates with variadic
arguments, so I tried something like that:

string interfaceGuid(string ifaceName)
{
  return ifaceName ~ "Guid";
}

mixin template EXPOSE_INTERFACE(string ifaceName)
{
  if (mixin(interfaceGuid(ifaceName)) == guid) { ... some casting }
}

mixin template EXPOSE_INTERFACES(T...)(T args)
{
  void QueryInterface(ref IComponent comp, string guid)
  {
    foreach (arg; args)
    {
      mixin EXPOSE_INTERFACE!arg;
    }
  }
}

But I got this:

component.d(8): Declaration expected, not 'if'
component.d(15): no identifier for declarator args
component.d(15): semicolon expected, not ')'
component.d(15): Declaration expected, not ')'
component.d(19): unrecognized declaration

Then I got confused and realized that my D is as sharp as is my German -
studied it for some time, but still has a problem to order a bread in a
store...

My questions are following:
- can mixin templates be used this way?
- why are they complaining?
- is there a better way to do this other than reproducing C macros?

Thanks,
Martin


More information about the Digitalmars-d-learn mailing list