pyCthon
pyCthon

Reputation: 12341

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

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

Upvotes: 2

Views: 1901

Answers (3)

Jamil Farooq
Jamil Farooq

Reputation: 141

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

}

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172934

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

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118350

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.

Upvotes: 2

Related Questions