【问题标题】:Cannot resolve type for template function无法解析模板函数的类型
【发布时间】:2014-06-23 15:40:22
【问题描述】:

我正在尝试在 D 中编写一些非常简单的代码,但我在使用其中一个标准库模板函数时遇到了一些问题(具体来说,nextPermutation 来自 std.algorithm)。

我要做的关键是创建泛数字数字的所有排列(即,包括所有值 1 到 9 的数字恰好一次)。

为此,我做了以下工作:

import std.algorithm;
import std.conv;

int[] pandigitals()
{
    char[] initial = "123456789".dup;
    auto pan = [to!int(initial)];
    while(nextPermutation!(initial)) {
       pan ~= to!int(initial);
    }
    return pan;
}

这给了我错误:

错误:无法解析 nextPermutation 的类型!(初始)

我也尝试过明确设置类型:

while(nextPermutation!("a<b", char[])(initial))

但是,这会给出一个错误,指出它无法匹配模板:

错误:模板实例 std.algorithm.nextPermutation!("a

调用的正确形式是什么?

【问题讨论】:

    标签: templates d phobos


    【解决方案1】:

    嗯,您的第一个问题是您将initial 作为模板参数而不是函数参数传递。 !() 用于模板参数。所以,而不是

    while(nextPermutation!(initial))
    

    你需要做的

    while(nextPermutation(initial)) {
    

    现在,这仍然会给你一个错误。

    q.d(10): Error: template std.algorithm.nextPermutation cannot deduce function from argument types !()(char[]), candidates are:
    /usr/include/D/phobos/std/algorithm.d(12351):        std.algorithm.nextPermutation(alias less = "a<b", BidirectionalRange)(ref BidirectionalRange range) if (isBidirectionalRange!BidirectionalRange && hasSwappableElements!BidirectionalRange)
    

    这是因为hasSwappableElements!(char[])false,并且根据nextPermutations 的模板约束,它必须是true 才能使用nextPermutations

    它是false,因为所有字符串都被视为dchar 的范围,而不是它们的实际元素类型。这是因为在 UTF-8 (char) 和 UTF-16 (wchar) 中,每个代码点有多个代码单元,因此对单个代码单元进行操作可能会破坏一个代码点,而在 UTF-32 ( dchar),每个代码点总是有一个代码单元。本质上,如果charwchar 的数组被视为charwchar 的范围,那么您将面临分解字符的高风险,因此您最终会得到字符片段而不是整个字符人物。所以,一般在 D 中,如果你想对单个字符进行操作,你应该使用dchar,而不是charwchar。如果您对 Unicode 不是很熟悉,我建议您阅读 Joel Spoelsky 撰写的 this article 关于该主题的文章。

    但是,不管为什么hasSwappableElements!(char[])false,它 false,所以你需要使用不同的类型。最简单的方法可能是将您的算法换成使用dchar[]

    int[] pandigitals()
    {
        dchar[] initial = "123456789"d.dup;
        auto pan = [to!int(initial)];
        while(nextPermutation(initial)) {
           pan ~= to!int(initial);
        }
        return pan;
    }
    

    【讨论】:

    • 谢谢,我有一个static assert 用于isBidirectionalRange!(char[]);,但忘记了hasSwappableElements 约束。
    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 2016-06-13
    • 2011-08-04
    • 2021-11-27
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多