Question

I have the following template class declaration:

template<void f(int)>
class A{
public:
    A(){
        struct sigaction sigact;
        ...
        if(sigact.sa_handler != f){
            ...
        }
    };
}

Can you tell me what this type of template is called? what is benefit of this template? This class is declared to install signal handler which is passed as f(int). Whenever we create an instance of this class, there is signal handler to be installed. I understand function templates and class templates. what is this template? I dont know why and what is benefit in this way?

Was it helpful?

Solution

Templates are parametrized types. In the case you brought, the name A refers to a family of types, one for each function of the form void f(int) that you pass to it. So, given the following declarations:

void print_int(int x);
void close_file(int x);
void handle_signal(int x);

A<print_int> p;
A<close_file> c;
A<handle_signal> s;

the variables p, c, and s have different (but related) types and the if block you highlighted above will only be entered if the function used to instantiate the template is NOT the same pointed-to by sigact.sa_handler.

OTHER TIPS

It's a mechanism to make the class call different functions depending on how it's created. If you create the class with a function that returns true, your class will behave different as it you passed it a function that returns struct of type sigaction.

How you use that flexibility is an even bigger question, and depends on both your creativity and your requirements. In your example, you're specifying that the function you pass will return void, which... might not be ideal in the context you're using it since you're using it to compare to something else. Remember, though, that templates allow this kind of stuff.

This might as well be part of an even subject: Policy-based design.

Think about polymorphism. With that class, you can pass any kind of function as a parameter, effectively making C++ as close to a functional language as it can get, by making functions first class citizens (which means you can pass them as arguments to other functions directly, without function pointers or delegates, and without relying on lambdas).

The whole 'strategy' design pattern follows this same approach. On the original book, an example is hinted to use templates instead of inheritance-based polymorphism, which results in a cleaner and faster approach, loosing some flexibility (the downside of the templates is that you need to know how you're gonna use classes before runtime).

Hope this clears it up a bit, try reading the links, it will be very illustrative! =)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top