【问题标题】:How to propagate an undefined number of template arguments? [duplicate]如何传播未定义数量的模板参数? [复制]
【发布时间】:2018-03-20 17:24:03
【问题描述】:

使用以下类,我希望能够创建指定Foo() 的实例来存储和调用函数,但是如何将必要的参数传递给函数call?

template<class R, class... Args> struct Foo {
    std::function<R(Args...)> func;

    Foo(const std::function<R(Args...)> &funcIn) : func(funcIn) {}

    R call(Args...) {
        return func(/* ? */);
    }
};

例如:

int main() {
    typedef typename Foo<int(int)> Bar;
    Bar x([](int y, int z){return y + z + 2;});
    std::cout << x.call(12, 7);
    return 0;
}

【问题讨论】:

标签: c++ c++11 templates variadic-templates multiple-arguments


【解决方案1】:

这很简单。只需添加参数名称即可。

R call(Args... args) {
    return func(args...);
}

【讨论】:

    【解决方案2】:

    为了简单

    R call (Args... as) {
        return func(as...);
    }
    

    如果Args... 类型是int、long、float 和其他不支持移动语法的简单类型,这应该可以正常工作。

    如果你想添加完美的转发,像

    template <typename ... As>
    R call (As && ... as) {
        return func(std::forward<As>(as)...);
    }
    

    --- 编辑---

    如果我根据 Smit Ycyken 理解正确(?),则此代码甚至无法编译。

    OP 原始代码中存在一些错误(class Foo 应该是 struct 或 make something public;main() 中的 typedef 是错误的)但以下更正的代码使用我的 g++ 编译还有我的叮当++

    #include <iostream>
    #include <functional>
    
    template<class R, class... Args> struct Foo {
        std::function<R(Args...)> func;
    
        Foo(const std::function<R(Args...)> &funcIn) : func(funcIn) {}
    
        R call (Args... as) {
           return func(as...);
        }
    };
    
    int main ()
     {
       typedef Foo<int, int, int> Bar;
       Bar x([](int y, int z){return y + z + 2;});
       std::cout << x.call(12, 7);
       return 0;
     }
    

    【讨论】:

    • 这里也一样。没有模板标题就出错了。给这个光头的人戴一顶帽子! R call (Args... as) {...}
    • @SmitYcyken - 第一个例子,第二个还是两者都有?
    • @SmitYcyken - 答案已修改;请问,你能解释一下我的回答有什么问题吗?
    猜你喜欢
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2020-12-17
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 2011-12-13
    相关资源
    最近更新 更多