2
votes

An interface template looks like this:

interface TemplateInterface(T) {
  T x();
}

This interface needs to be used as a parameter for a function, but I'd like to avoid defining the template type in the function signature. Is there some way to just have the function signature accept whatever template type is being passed to the function, like a templated function?

For example:

// no good, do not want to constrain template type at this point
void func1(TemplateInterface!int parm1) {...

// this would be better, but the syntax is wrong apparently
void func1(TemplateInterface parm1) {...
2

2 Answers

2
votes

I believe what you want is

void func1 (T) (TemplateInterface!T parm1) {...

Here, func1 has a compile-time parameter T, which is used in the argument's type TemplateInterface!T, and a run-time parameter parm1 of the aforementioned type.

A more complete example:

import std.stdio;

interface TemplateInterface(T) {
    T x();
}

class Instance(T) : TemplateInterface !(T) {
    T x() {return cast (T) (1.2345);}
}

void func1 (T) (TemplateInterface!T parm1) {
    writeln (typeof(parm1.x()).stringof, " ", parm1.x());
}

void main() {
    auto a = new Instance !(int) ();
    auto b = new Instance !(real) ();
    func1(a); // int 1
    func1(b); // real 1.2345
}
0
votes

You can use a template function with a template constraint to achieve this:

import std.traits: isInstanceOf;

interface TemplateInterface(T) {
    T x();
}

void func1(TemplateInterfaceInstance)(TemplateInterfaceInstance parm1)
        if(isInstanceOf!(TemplateInterface, TemplateInterfaceInstance))
{ ...

The template constraint is not strictly needed, but you get better error messages with it when trying to pass something to func1 which is not an instance of TemplateInterface.