3

我正在尝试定义一个类,该类具有存储在联合中的不同数量参数的函数。该类使用函数对象和必要的参数进行初始化。我在标记为 (1) 和 (2) 的位置收到这些编译器错误

(1) '_' 的析构函数被隐式删除,因为变量字段 'f_V' 有一个非平凡的析构函数

(2) 'MyClass' 的析构函数被隐式删除,因为字段 'functions' 有一个已删除的析构函数

我只是想声明一个不同函数对象的联合,并根据传入的参数能够选择适当的函数并调用它。为什么我会收到这些错误,我应该如何重写这段代码?

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 中 () 运算符的定义,但它只是使用正确的参数调用正确的函数对象。

如果您看到更好的设计方法,很好,请指引我正确的方向。谢谢!

4

1 回答 1

3

你可以使用 C++11 的无限制联合特性来做你想做的事。您将需要在构造/删除适当活动成员的联合上实现自定义构造函数和析构函数。

于 2013-09-04T18:03:46.630 回答