d该别名有啥问题

原文

auto s = 1234.to!string.map!q{a - '0'}.sum;

正常.但

alias comb = to!string.map!q{a - '0'}

报错.

import std;
alias comb = map!q{a - '0'};
void main()
{
    auto s = 2234.to!string.map!q{a - '0'}.sum;
    s.to!string.comb.sum.writeln;
    // 工作: "2"
}

简单说明:
到!串(to!string)是期望1个参数的函数,但在别名中,你没有提供该参数.请把别名转换为λ式:

alias comb = x => x.to!string.map!q{a - '0'}

复杂解释:
到(to)是如下定义的模板:

// https://github.com/dlang/phobos/blob/master/std/conv.d
template to(T)
{
    T to(A...)(A args)if (A.length > 0)
    {
        return toImpl!T(args);
    }
    // 为简洁,省略了一些重载
}

至少需要2个模板参数,第一个参数是(用到!串)显式传递的外部模板,其他是从传递到(to)函数中推导的.因为没有传递参数给到!串,则不会实例化内部模板.

基本上,你在试按参数未实例化的模板传递给映射(map).这是非常奇特情况,所以可能没有专门错误消息,或遇见了编译器中的八哥.
一个合理方法,由于目标是操作数字,因此可直接转换为char类型:

import std.algorithm : map, sum;
import std.conv : toChars;

alias comb = (uint x) => x.toChars.map!"a - '0'";
void main()
{
    auto s = 2234.comb.sum;
    assert(s.comb.sum == 2);
}
posted @ 2023-01-08 22:43  zjh6  阅读(24)  评论(0)    收藏  举报  来源