如何解决d中的"冲突"错误?

lim*_*imp 3 conflict namespaces d

我正在尝试编译一些D.我编写的代码也使用了std.stringstd.algorithm.我的一个函数调用indexOf一个字符串:不幸的是,显然还有一个indexOf函数std.algorithm,并且编译器不喜欢它:

assembler.d(81): Error: std.algorithm.indexOf!("a == b", string, immutable(char)).indexOf at /usr/share/dmd/src/phobos/std/algorithm.d(4431) conflicts with std.string.indexOf!(char).indexOf at /usr/share/dmd/src/phobos/std/string.d(334)
assembler.d(81): Deprecation: function std.algorithm.indexOf!("a == b", string, immutable(char)).indexOf is deprecated
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?在C++中,我可以使用::明确说出我所在的命名空间...... D怎么样?

Jon*_*vis 7

如果要std.string.indexOf显式调用,则执行std.string.indexOf(str, c)而不是indexOf(str, c)str.indexOf(c).

或者您可以使用别名:

alias std.string.indexOf indexOf;
Run Code Online (Sandbox Code Playgroud)

如果你把你调用其中的函数内indexOf,那么就应该再考虑indexOfstd.string.indexOf对函数的其余部分.或者如果你把它放在模块级别,那么它将影响整个模块.

然而,由于错误,UFCS(通用函数调用语法)目前不与本地别名工作,所以如果你把别名的函数中,你必须做indexOf(str, c)的,而不是str.indexOf(c).

第三种选择是使用选择性导入:

import std.string : indexOf;
Run Code Online (Sandbox Code Playgroud)

使用该导入,仅从indexOfstd.string导入,当您使用时indexOf,它将使用该string版本(即使您还导入std.algorithm).除了选择性导入以外,你甚至可以定期导入std.string来获取std.string的其余部分,而选择性导入仍然可以解决冲突(在这种情况下,它与导入std.string然后真的没那么不同别名indexOf).但是,由于存在错误,选择性导入始终被视为公共导入,因此indexOf在模块中进行选择性导入会影响导入它的每个模块(可能导致新的冲突),因此您可能希望在此时避免使用它.