【问题标题】:Sending a templated function as an argument to a templated function in D将模板化函数作为参数发送到 D 中的模板化函数
【发布时间】:2012-03-27 05:24:08
【问题描述】:

我正在尝试将 D 的 sort 函数作为模板参数发送给 pipe 函数。当我使用不带模板参数的sort 时,它可以工作:

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

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

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

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

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

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

为什么会这样? sort!"b&lt;a" 独立工作,它具有与sort 相同的参数和返回类型,那么为什么pipe 接受sort 而不是sort!"b&lt;a"?我尝试做的事情有正确的语法吗?

更新

好的,我已尝试包装 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);
}

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

【问题讨论】:

    标签: templates d dmd


    【解决方案1】:

    是的,这是因为额外的模板参数——特别是Range 参数。问题可以简化为

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

    实例化sort!"b&lt;a" 将失败,因为范围未确定。函数调用sort2!"b&lt;a"([1,2,3]) 有效,因为参数[1,2,3] 可以告诉编译器类型Range 是int[]。这被称为“隐式函数模板实例化 (IFTI)”。但 IFTI 仅在用作函数时才有效。在您的用例中,sort!"b&lt;a" 在没有提供所有参数的情况下被实例化,因此出现错误。

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

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

    或者您可以提供所有必需的模板参数。这使得代码非常不可读。

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

    【讨论】:

    • 我明白了...我认为pipe 模板,它隐式地将参数的类型作为模板参数,应该将该参数传递给第一个管道函数,但我发现这不是案例。
    • @IdanArye: @IdanArye: pipe 永远无法做到这一点,因为人们可以将它与论点分开(alias pipe!(f) piped; 然后很多行之后piped([1,2,3]);
    • 不应该像 aliasing 这样使 piped 本身成为模板函数吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多