简体   繁体   中英

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?

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 .

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM