d:模板限制,显示给定类型是否具有可比性
问题描述:
我怎么会写为下面的结构d:模板限制,显示给定类型是否具有可比性
struct Foo (T, U) {
}
模板约束表明,这两个T
和U
必须与使用<
?我的意思是两个T
可以与<
比较,两个U
可以与<
比较 - 一个T
和U
可以是无法比拟的。
答
我相信这会做你问什么,但有可能是一个更简洁的解决方案:
struct Foo (T, U) if (is(typeof(T.init < T.init) : bool)
&& is(typeof(U.init < U.init) : bool)
{ }
你可以清理有点用的模板:
enum bool isSelfComparable(T) = is(typeof(T.init < T.init) : bool);
struct Foo (T, U) if (isSelfComparable!T && isSelfComparable!U) { }
答
最简洁我现在能想到的方式是
struct Foo(T, U)
if(is(typeof(T[0] < T[0])) && is(typeof(U[0] < U[0])))
{
}
但我可能会声明它为
struct Foo(T, U)
if(is(typeof(T.init < T.init)) && is(typeof(U.init < U.init)))
{
}
因为它更直接。有些人可能会使用静态数组混淆,而这不是必需的。但从技术上讲,这个时间有点短。
在murphyslaw's answer的: bool
部分实际上不是必要的,因为<
不能什么,但bool
造成的,因为编译器将<
,<=
,>
,并>=
对用户自定义类型调用opCmp
,所以程序员没有机会让它们产生除bool
以外的任何内容(当然,对于内置类型,比较运算符产生bool
)。但murphyslaw's answer也可以工作。这只是比所需的更详细。
是: bool
或== bool
将被要求,如果你想接受一个谓语,而不是直接使用比较操作符(从那以后,你在处理任意功能)将是主要的地方,那就是通常会在通用在Phobos最终做的算法。例如find
的重载之一的签名是
InputRange find(alias pred = "a == b", InputRange, Element)
(InputRange haystack, Element needle)
if (isInputRange!InputRange &&
is (typeof(binaryFun!pred(haystack.front, needle)) : bool))
{...}
但是,如果你在直接使用比较操作,然后简单地检查它们编译计划就足够了。