使用模板比较器的完整示例 [英] Full example of using template comparator
问题描述
我尝试使用模板参数 std :: less
, std :: greater
或。这是对此问题的跟进,因为答案没有提供完整的示例,我无法成功使用模板比较器。
I am trying to a template class driven with a template parameter of std::less
, std::greater
or. This is a follow up to this question since, the answer doesn't provide a full example and I am unable to successfully use the template comparator.
#include <functional>
#include <algorithm>
template <typename C>
class Test
{
int compare(int l, int n, int x, int y)
{
public:
bool z = C(x, y);
if(l < n && z)
{
return 1;
}
else
{
return 2;
}
}
};
int main() {
Test<std::less<int>> foo;
Test<std::greater<int>> bar;
foo.compare(1, 2, 3, 4);
bar.compare(1, 2, 3, 4);
}
推荐答案
c> C (即 std :: less< int>
或 std :: greater< int>
)是类型名,而不是实例。 bool z = C(x,y); 在
C == std :: less< int>
,因为 C(x,y)
将被解释为 std :: less< int>
这将失败,因为 std :: less
没有这样的构造函数,并且 std :: less
不能转换为 bool
。
Note that C
(i.e. std::less<int>
or std::greater<int>
) is the type name, not the instance. bool z = C(x, y);
won't work when C==std::less<int>
, because C(x, y)
will be interpreted as the construction of std::less<int>
, which will fail because std::less
doesn't have such constructor, and std::less
can't be converted to bool
.
您可能意味着调用 operator c>在
C
的实例上,可以将其更改为
You might mean call operator()
on the instance of C
, you could change it to
bool z = C()(x, y);
这篇关于使用模板比较器的完整示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!