是否可以实施此类行为?它不必使用继承,我只想实现通用参数传递的模板方法设计模式(使用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;
}
答案 0 :(得分:3)
这几乎是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;
}