c++ - 可变参数 C++ 模板解压后终止?

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

我正在尝试使用 C++ 可变参数模板解压缩变量类型的参数列表,我将如何删除以下人工示例中的“T”对象:

struct Test
{
    template <typename T, typename... Args>
    void foo(T t, int i, Args... args) { foo(t, args...); }

    template <typename T, typename... Args>
    void foo(T t, double d, Args... args) { foo(t, args...); }

    template <typename T>
    void foo(T t) { }
};

struct DummyObject { };

然后像这样执行:

DummyObject dummy;
Test test;
test.foo(dummy, 4, 5.0, 6, 7.0, 8.0, 9);

我想完全消除传入“虚拟”对象的需要,我只是想不出在这种情况下最终的“foo”函数应该是什么样子。

最佳答案

让我稍微充实一下您的样本:

struct Test
{
    template <typename T, typename... Args>
    void foo(T t, int i, Args... args) { doIThing(i); foo(t, args...); }

    template <typename T, typename... Args>
    void foo(T t, double d, Args... args) { doDThing(d);  foo(t, args...); }

    template <typename T>
    void foo(T t) { }
};

因此有两个函数执行实际工作:doIThingdoDThing。你 99% 都答对了,只需...删除 T。

struct Test
{
    template <typename... Args>
    void foo(int i, Args... args) { doIThing(i); foo(args...); }

    template <typename... Args>
    void foo(double d, Args... args) { doDThing(d);  foo(args...); }

    void foo() { }
};

在这里运行:http://coliru.stacked-crooked.com/a/b35ac716cf2960b3

关于c++ - 可变参数 C++ 模板解压后终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51315813/

相关文章:

c++17 通过生成预先声明的类型列表的笛卡尔积来制作 std::variant

c++ - 模板参数推导不一致

matlab - 从变量读取的可变长度 MATLAB 参数

c可变参数函数,相同的参数,不同的格式

swift - 如何接受 CGFloat 或 CGFloats 数组作为函数参数?

c++ - 将 cuBLAS 与来自 Thrust 的复数结合使用

c++ - POD 结构或标准布局类型的成员是否保证根据其对齐要求对齐?

c++ - google protobuf 编译器不为服务标签生成类?

c++ - 函数重载 : empty parameter list vs parameter pack

c++ - 模板类的模板友元函数