c++templatestemplate-method-pattern

Create a class method template, that will use function implemented later


Is it possible to implement such behaviour? It does not have to use inheritance, I just want to implement template method design pattern with generic arguments passing (with c++ templates).

class A {
public:
    template<typename ...tArgs>
    void call(tArgs ...vArgs) {
        for (int i = 0; i < 5; ++i)
            impl(vArgs...);
    }
};

class B : public A {
public:
    void impl() {}
    void impl(int) {}
};

int main() {
    B b;
    b.call();    // ok
    b.call(1);   // ok
    b.call("");  // compile error, no method to call inside 'call'
    return 0;
}

Solution

  • This is almost a classic example of the CRTP pattern, just a few small changes required:

    // A is now a template taking its subclass as a parameter
    template <class Subclass>  
    class A {
    public:
        template<typename ...tArgs>
        void call(tArgs ...vArgs) {
            for (int i = 0; i < 5; ++i)
                // need to static cast to Subclass to expose impl method
                static_cast<Subclass*>(this)->impl(vArgs...);
        }
    };
    
    // pass B into A template (the "curiously recurring" part)
    class B : public A<B> {
    public:
        void impl() {}
        void impl(int) {}
    };
    
    int main() {
        B b;
        b.call();    // ok
        b.call(1);   // ok
        // b.call("");  // will cause compile error, no method to call inside 'call'
        return 0;
    }