2014-12-03 51 views

回答

7

我相信这会做你问什么,但有可能是一个更简洁的解决方案:

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) { } 
2

最简洁我现在能想到的方式是

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)) 
{...} 

但是,如果你在直接使用比较操作,然后简单地检查它们编译计划就足够了。

相关问题