functions/delegates 不匹配重载模板

functions/delegates not matching overloaded template

看起来 D 在将函数和委托传递给它们时在选择正确的重载模板时遇到了问题。 举个例子:

import std.stdio;

void test()(string a){
    writeln(a);
}

void test(Ret, Args...)(Ret function(Args) fn){
    writeln(fn(1, 2));
}

void test(T)(T a){
    assert(0);
}

void main(){
    test("something");
    test((int a, double b){
        return "works";
    });
}

理论上,这应该打印 something\nworks。但这是输出:

something
core.exception.AssertError@test.d(15): Assertion failure
...

删除 void test(T)(T a) 时有效。

  1. 为什么选择的匹配项是 (T a)
  2. 有没有办法在不显式传递参数且不从 (T a) 中调用 (Ret function(Args)) 的情况下强制进行正确的选择?

来自template specialization docs

If both a template with a sequence parameter and a template without a sequence parameter exactly match a template instantiation, the template without a TemplateSequenceParameter is selected.

您可以通过使用 isSomeFunction 添加约束来解决它:

void test(T)(T a) if (!isSomeFunction!T) {
    assert(0);
}