fduff
fduff

Reputation: 3831

Need clarification on C++ template format

I'm going through some template sample code and there's one thing I don't get.

Take a template methode:

template<class Seq, class T, class R>
void apply(Seq &sq, R(T::*f)() const) {
    typename Seq::iterator it = sq.begin();
    while(sq.end() != it) {
        ((*it++)->*f)();
    }
}

A sample class:

class MyClass {    
public:
    MyClass() {}
    void doSomething() const {
        std::cout << "doing stuff..." << std::endl;
    }
};

And the test code:

void testMyClass() {
    vector<MyClass*> v;
    for(size_t i = 0; i < 5; ++i) {
        v.push_back(new MyClass());
    }
    // call a member methode on all elements in container
    apply(v, &MyClass::doSomething);
}

I would be grateful if someone could explain me what is that class R for, as defined in the template definition?

Upvotes: 1

Views: 65

Answers (2)

leemes
leemes

Reputation: 45745

class R refers to the return type of the function pointer being passed to the function apply. It is automatically deduced from the actually passed function pointer type, so you never really need to care about it when calling apply.

The implementation of apply discards the return value of the function, so you could simply force the passed function to return void:

template<class Seq, class T>
void apply(Seq &sq, void(T::*f)() const) {
    typename Seq::iterator it = sq.begin();
    while(sq.end() != it) {
        ((*it++)->*f)();
    }
}

However, now you restrict the call site to only pass such function pointers. Sadly, a pointer to a function which returns something isn't implcitly convertible to one which doesn't, although it would be pretty "intuitive".

So when you take a function pointer as an argument, and you don't care about the return type, it's better to accept "any" return type than "none".

Upvotes: 2

R Sahu
R Sahu

Reputation: 206747

class R in the template is used to deduce the return type of the function. In your case, it is deduced to be of type void.

Upvotes: 2

Related Questions