2

Motivated by this example using std::less/std::greater. Is it possible to use std::min or std::max as a template comparator?

The following example throws the error:

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);
}
Community
  • 1
  • 1
pyCthon
  • 11,746
  • 20
  • 73
  • 135

3 Answers3

2

std::min<int> and std::max<int> are not types. They are functions.

Test<std::min<int>> 

The Test template expects its parameter to be a class (or, rather, a type), not a function. The template is declared as:

template <typename C> class Test

typename means that the template parameter is a class/type.

Additionally, the template declares a method called "compare". main() attempts to invoke a method called "run". That would be another problem.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
2

Note std::min and std::max are function templates. If you want to use them as template parameters, you need to declare them as non-type template parameter, such as function pointer:

template <const int& (*C)(const int&, const int&)>
class Test
{
public:
    int compare(int x, int y)
    {
        return C(x, y);
        //      ~~ Note no () here
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

It std::min and std::max are functions not classes. Probably using Functor class template to wrap std::min/max functionality is also a better option as in code below:

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

}
Jamil Farooq
  • 131
  • 2
  • 9