0

是否有可能实现这种行为?它不必使用继承,我只想通过泛型参数传递(使用 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;
}
4

1 回答 1

3

这几乎是CRTP 模式的经典示例,只需进行一些小改动:

// 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;
}
于 2017-04-05T08:41:24.837 回答