创建一个 class 方法模板,将使用稍后实现的功能

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

是否可以实现这种行为?它不必使用继承,我只是想实现带有通用参数传递的模板方法设计模式(使用c++模板)。

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;
}

这几乎是一个经典的例子CRTP pattern,只需要做一些小改动:

// 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;
}