将模板化函数作为参数发送到D中的模板化函数

Ida*_*rye 5 templates d dmd

我正在尝试将D sort函数作为函数的模板参数发送pipe.当我使用sort没有模板参数时,它工作:

import std.stdio,std.algorithm,std.functional;

void main()
{
    auto arr=pipe!(sort)([1,3,2]);
    writeln(arr);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用sort模板参数时:

import std.stdio,std.algorithm,std.functional;

void main()
{
    auto arr=pipe!(sort!"b<a")([1,3,2]);
    writeln(arr);
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误 - main.d(5): Error: template instance sort!("b<a") sort!("b<a") does not match template declaration sort(alias less = "a < b",SwapStrategy ss = SwapStrategy.unstable,Range)

为什么会这样?sort!"b<a"它自己工作,它有相同的参数和返回类型sort,所以为什么pipe接受sort但不是sort!"b<a"?我尝试做的是否有正确的语法?

UPDATE

好的,我试图包装该sort功能.以下代码有效:

import std.stdio,std.algorithm,std.functional,std.array;

template mysort(string comparer)
{
    auto mysort(T)(T source)
    {
        sort!comparer(source);
        return source;
    }
}

void main()
{
    auto arr=pipe!(mysort!"b<a")([1,3,2]);
    writeln(arr);
}
Run Code Online (Sandbox Code Playgroud)

那么为什么原版不起作用呢?这是因为额外的模板参数sort需要吗?

ken*_*ytm 5

是的,因为额外的模板参数 - 特别是Range参数.问题可以减少到

size_t sort2(alias f, Range)(Range range)
{
    return 0;
}
alias sort2!"b<a" u;
Run Code Online (Sandbox Code Playgroud)

实例化sort!"b<a"将失败,因为未确定范围.函数调用sort2!"b<a"([1,2,3])有效,因为参数[1,2,3]可以告诉编译器Range类型int[].这称为"隐式函数模板实例化(IFTI)".但IFTI仅在用作函数时才有效.在您的用例中,sort!"b<a"实例化时不提供所有参数,从而导致错误.

这可以通过使输入成为函数文字来修复,这与您的mysort解决方案类似:

 auto arr = pipe!(x => sort!"b<a"(x))([1,3,2]);
Run Code Online (Sandbox Code Playgroud)

或者您可以提供所有必需的模板参数.这使得代码非常难以理解.

auto arr = pipe!(sort!("b<a", SwapStrategy.unstable, int[]))([1,3,2]);
Run Code Online (Sandbox Code Playgroud)