c++ - 使用可变函数作为模板参数

标签 c++ templates variadic-templates variadic-functions

我想让下面的代码在不改变 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;
    }
};

online compiler

关于c++ - 使用可变函数作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909373/

相关文章:

c++ - 获取当前的 ModelView 矩阵

c++ - 可变参数模板 : One method per template argument

c++ - 使用 Visual Studio 2013 pro 更新 3(或 4)在 Windows 8.1 上构建 Chromium。

c++ - 由 C++ 编译器优化时,F2C 翻译的代码会中断

c++ - 如何将此内联汇编代码转换为 x64 汇编

c++ - 此 C++ 运行时警告的含义是什么

c++ - 可变参数函数指针参数的模板参数推导 - 处理不明确的情况

c++ - 模板特化和 enable_if 问题

C++17 可变参数模板折叠

c++ - 使用可变参数模板函数围绕类实现基于 pImpl 的包装器