Full example of using template comparator

假如想象 提交于 2019-12-24 09:39:52

问题


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);
}

回答1:


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.

You might mean call operator() on the instance of C, you could change it to

bool z = C()(x, y);


来源:https://stackoverflow.com/questions/38558746/full-example-of-using-template-comparator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!