我正在尝试定义一个类,该类具有在 union 中存储不同数量参数的函数。该类使用函数对象和必要的参数进行初始化。我在标记 (1) 和 (2) 的位置收到这些编译器错误
(1) '_' 的析构函数被隐式删除,因为变体字段 'f_V' 具有非平凡的析构函数
(2) “MyClass”的析构函数被隐式删除,因为字段“functions”具有已删除的析构函数
我只是想声明一个不同函数对象的 union ,并根据传入的参数选择合适的函数并调用它。为什么会出现这些错误以及我应该如何重写此代码?
template<typename VARIABLE> struct MyClass {
MyClass(VARIABLE *p, const std::function<void (VARIABLE&)>& f) {
functions.f_V = f;
...
}
protected:
union _ {
std::function<void (VARIABLE &)> f_V; // (1)
std::function<void (const VARIABLE &, VARIABLE &)> f_vV;
std::function<void (const VARIABLE &, const VARIABLE &, VARIABLE &)> f_vvV;
std::function<void (const VARIABLE &, const VARIABLE &, const VARIABLE &, VARIABLE &)> f_vvvV;
} functions; // (2)
...
};
编辑:我正在尝试在容器中完成具有可变参数列表的 lambda 函数的存储。像这样:
std::vector<MyClass<MyVariable>> myContainerOfLambdas;
MyVariable A,B,TO;
auto lambda1 = [this](const MyVariable& a, MyVariable& to) { ... };
myContainerOfLambdas.push_back(MyClass<MyVariable>(A,TO,lambda1));
auto lambda2 = [this](const MyVariable& a, const MyVariable& b, MyVariable& to) { ... };
myContainerOfLambdas.push_back(MyClass<MyVariable>(A,B,TO,lambda2));
...
// iterate over the stored MyClass objects holding the lamda functions and the parameters
// to call them
for(MyClass<MyVariable> & e:myContainerOfLambdas) {
e(); // here the appropriate lambda function will be invoked with the appropriate values
// stored in MyClass
}
注意:为简洁起见,我省略了 MyClass 中 () 运算符的定义,但它只是使用正确的参数调用正确的函数对象。
如果您看到更好的设计方法,那很好,请指导我正确的方向。谢谢!
最佳答案
您可以使用 unrestricted unions feature C++11 做你想做的事。您需要在构造/删除适当事件成员的 union 上实现自定义构造函数和析构函数。
关于c++ - 在 C++11 中结合使用 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18619360/