相关疑难解决方法(0)

如何存储可变参数模板参数?

是否可以以某种方式存储参数包供以后使用?

template <typename... T>
class Action {
private:        
    std::function<void(T...)> f;
    T... args;  // <--- something like this
public:
    Action(std::function<void(T...)> f, T... args) : f(f), args(args) {}
    void act(){
        f(args);  // <--- such that this will be possible
    }
}
Run Code Online (Sandbox Code Playgroud)

然后是:

void main(){
    Action<int,int> add([](int x, int y){std::cout << (x+y);}, 3, 4);

    //...

    add.act();
}
Run Code Online (Sandbox Code Playgroud)

c++ variadic-templates c++11

79
推荐指数
3
解决办法
3万
查看次数

使用`std :: function <void(...)>`来调用非void函数

前一段时间我用std::function的很像:

std::function<void(int)> func = [](int i) -> int { return i; };
Run Code Online (Sandbox Code Playgroud)

基本上,我这样做是因为我想在a中存储不同的函数对象std::function,但我不想限制这些函数的返回类型.由于这似乎有效,我接受了它.但我不相信它是安全的,我也无法找到任何文件.有谁知道这种用法是否合法?或者更一般地说,对象的规则是什么,可以安全地分配给std::function

编辑

为了澄清,我关心的问题是lambda函数返回一个int,而func声明返回类型void.我不确定这是否正常,特别是一旦打电话func().

c++ return-type c++11 std-function

19
推荐指数
1
解决办法
6574
查看次数