0

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;
}
omicronns
  • 357
  • 1
  • 10
  • 1
    Not quite clear what you want to achieve. In your example, there is no overload for `const char*` at compile time, so you get that compile error. – Alexander Lapenkov Apr 05 '17 at 08:33
  • [That's not the only error in that code.](http://coliru.stacked-crooked.com/a/6dc7e20197d5f898) None of those invokes to `call` work because `impl` cannot resolve. – WhozCraig Apr 05 '17 at 08:38
  • This example does not work, event without last call. I only described desired behaviour. – omicronns Apr 05 '17 at 08:38

1 Answers1

3

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;
}
Joseph Ireland
  • 2,465
  • 13
  • 21