使用模板比较器的完整示例 [英] Full example of using template comparator

查看:163
本文介绍了使用模板比较器的完整示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用模板参数 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆