【发布时间】:2018-10-21 04:01:26
【问题描述】:
我想让以下代码在不更改 Child1 和 Child2 类的情况下运行:
#include <iostream>
int triple(int a) {
return a * 3;
}
int add(int a, int b) {
return a + b;
}
template<int (*F)(int)>
class Parent {
public:
Parent(int a) {
std::cout << "constructed: " << F(a) << std::endl;
}
};
class Child1 : Parent<triple> {
public:
Child1(int a) : Parent(a) {}
};
/*class Child2 : Parent<add> {
public:
Child2(int a, int b) : Parent(a, b) {}
};*/
int main() {
Child1 child(4);
//Child2 child(5, 6);
return 0;
}
例如,您可以看到,Child1 继承自 Parent,该 Parent 已使用 triple 函数实例化。因此,当Child1 被实例化为 4 时,它会输出“constructed: 12”。
相比之下,Child2 被注释掉了,因为它显然还不能工作。在主函数中,我试图将两个参数传递给Child2 构造函数,就像底层add() 函数所期望的那样。然而,Parent 的构造函数只接受一个参数,并且可能需要在它前面加上template<typename Args...> 才能解决问题。此外,Parent 类将需要一个模板参数,如int (*F)(Args...)。最终,像 main 函数一样构造一个Child2 实例应该输出“constructed: 11”。
我怎样才能做到这一点,即创建一个模板参数,它是一个可以有任意数量参数的函数?同样,请注意 Parent 类的代码是唯一可以更改的内容。
【问题讨论】:
标签: c++ templates variadic-templates variadic-functions