std::min/std::max作为模板比较器

std::min/std::max as template comparators

本文关键字:std 比较器 max min      更新时间:2023-10-16

受本例使用std::less/std::greater的启发。是否可以使用std::minstd::max作为模板比较器?

以下示例引发错误:

error: type/value mismatch at argument 1 in template parameter list for 'template<class C> class Test'

#include <functional>
#include <algorithm>
template <typename C>
class Test
{
public:
    int compare(int x, int y)
    {
        return C()(x, y);
    }
};
int main() {
    Test<std::min<int>> foo;
    Test<std::max<int>> bar;
    foo.compare(1, 2);
    bar.compare(1, 2);
}

注意std::minstd::max是函数模板。如果要将它们用作模板参数,则需要将它们声明为非类型模板参数,例如函数指针:

template <const int& (*C)(const int&, const int&)>
class Test
{
public:
    int compare(int x, int y)
    {
        return C(x, y);
        //      ~~ Note no () here
    }
};

std::min<int>std::max<int>不是类型。它们是函数。

Test<std::min<int>> 

Test模板希望其参数是类(或者更确切地说是类型),而不是函数。模板声明为:

template <typename C> class Test

typename表示模板参数是一个类/类型。

此外,该模板还声明了一个名为"compare"的方法。main()尝试调用一个名为"run"的方法。那将是另一个问题。

它std::min和std::max是函数而不是类。可能使用Functor类模板包装std::min/max功能也是一个更好的选择,如下代码所示:

#include <iostream>
#include <functional>
#include <algorithm>
template <typename C>
class Test
{
public:
    int compare(int x, int y)
    {
        return C()(x, y);
    }
};
template<typename T>
class MinComp {
public:
    T operator ()(T x, T y) {
        return std::min<T>(x,y);
    }
};
int main() {
    Test<MinComp<int>> foo;
     std::cout<<foo.compare(5, 2);
}