【问题标题】:Variadic C++ Templates Termination After Unpack?解压后可变 C++ 模板终止?
【发布时间】:2018-07-12 23:33:49
【问题描述】:

我正在尝试使用 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”函数应该是什么样子。

【问题讨论】:

  • 要回答这个问题,我们需要知道你对id 参数做了什么。

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


【解决方案1】:

让我稍微充实一下你的示例:

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

【讨论】:

    【解决方案2】:

    其他方法是删除递归调用并有类似的东西:

    struct Test
    {
        template <typename... Args>
        void foos(Args... args)
        {
            (foo(args), ...); // C++17 fold expression
    #if 0 // C++11 or C++14
            const int dummy[] = {0, (foo(args), 0)...};
            static_cast<void>(dummy); // avoid warning for unused variable
    #endif
        }
    
        void foo(int t) { /*...*/ }
    
        void foo(double t) { /*...*/ }
    
        template <typename t> void foo(T t) { /**/ }
    
    };
    

    然后使用它:

    Test test;
    test.foos(4, 5.0, 6, 7.0, 8.0, 9);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多