The presence of a class or function as a template parameter

I was not sure what to look for, so I will try to explain as best as possible. In STL std::setis defined as

template <class Key, class Compare, class Allocator> class set;

From http://cplusplus.com :

Compare : Comparison class: a class that takes two arguments of the same type as the elements of the container and returns bool. The expression comp (a, b), where comp is an object of this comparison class, and a and b are elements of the container [...] . It can be either a class that implements a function call operator, or a pointer to a function [...] .

I am talking about a template parameter Compare.

So, if I wrote a template class that has a template parameter, which is a class that implements a function call operator, I would write

template <class T, class Combine>
class MyClass
{
public:
    Combine func;
    MyClass()
    {
        func = Combine();
    }
    T do_it(T a, T b)
    {
        return func(a, b);
    }
};

class IntCombine
{
public:
    int operator () (int a, int b)
    {
        return a + b;
    }
};

//...
MyClass<int, IntCombine> ob;
ob.do_it(4, 5);

Or, if I wrote it, so the second parameter to the template is the function:

template <class T, T Combine(T, T)>
class MyClass
{
public:
    Combine func;
    MyClass()
    {
        func = Combine;
    }
    T do_it(T a, T b)
    {
        return func(a, b);
    }
};

int IntCombine(int a, int b)
{
    return a + b;
}

//...
MyClass<int, IntCombine> ob;
ob.do_it(4, 5);

However, in STL you can use the specified class anyway. How is this implemented? The above code only works if the second template parameter in my definition obis either a class that implements operator ()or a function, but I cannot write MyClassto make both work.

My examples may look pretty useless. Basically I want to write a container that can combine elements, and this is common as STL containers.

+3
1

, ob (), , , MyClass, .

, :

template <typename F>
struct foo {
    F f;
    void call() {
        f();
    }
};

void function() {
    std::cout << "function called" << std::endl;
}

int main() {
    foo<void(*)()> a = { function };
    a.call();
}

std::set. , , , ( void (*)()). .

0

Source: https://habr.com/ru/post/1781070/


All Articles