我想让下面的代码在不改变 Child1
的情况下工作和 Child2
所有类(class):
#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
已使用 triple
实例化功能。因此,当 Child1
用 4 实例化,它输出“constructed: 12
”。
相比之下,Child2
被注释掉了,因为它显然还不起作用。在主函数中,我试图将两个参数传递给 Child2
构造函数,就像底层 add()
函数期望它。然而,Parent
的构造函数只接受一个参数,可能需要 template<typename Args...>
在它前面的解决方案。此外,Parent
类将需要一个模板参数,如 int (*F)(Args...)
.最终,构建一个 Child2
与主函数一样的实例应输出“constructed: 11
”。
我怎样才能做到这一点,即创建一个模板参数,它是一个可以有任意数量参数的函数?同样,请注意 Parent
类的代码是唯一可以更改的。
最佳答案
在 C++17 中,您可以使用推导的非类型模板参数并使构造函数成为可变参数模板:
template<auto x_pointer_to_function>
class Parent
{
public:
template<typename... x_Args>
Parent(x_Args &&... args)
{
std::cout << "constructed: " << ((*x_pointer_to_function)(::std::forward<x_Args>(args)...)) << std::endl;
}
};
关于c++ - 使用可变函数作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909373/