1

在使用 boost::variant 时,我不断收到错误提示“没有匹配的函数调用”。下面是我的代码片段。

struct Output {
    int a;
    float b;
}
    
typedef boost::variant<ClassA<X, Y>, ClassA<>> ClassAGeneric;

class Operation: public boost::static_visitor<Output>
{
public:
    double d;
    int a;
    float b;
    
    Output operator()(ClassA<X, Y> obj) const
    {
        obj.operate(d, a, b);
        return (Output) {a, b};
    }
    
    Output operator()(ClassA<> obj) const
    {
        obj.operate(d, a, b);
        return (Output) {a, b};
    }
};

我在定义的第一个 operator()的obj.operate()调用中收到此错误。

我尝试传递模板,就像另一个答案中提到的那样,但我仍然看到一个错误。

obj.operate<X,Y>(d,a,b);

有人可以帮我解决这个问题吗?

我也可以在这里给出确切的场景:

struct Output{
  Row<size_t> predictions;
  mat probabilities;
};
typedef boost::variant<RandomForest<GiniGain, RandomDimensionSelect>, RandomForest<>> RandomForestGeneric;

class Operation: public boost::static_visitor<Output>
{
public:
    mat dataset;
    Row<size_t> predictions;
    mat probabilities;
    
    Output operator()(RandomForest<GiniGain, RandomDimensionSelect> obj) const
    {
        obj.Classify(dataset, predictions, probabilities);
        return (Output) {predictions, probabilities};
    }
    
    Output operator()(RandomForest<> obj) const
    {
        obj.Classify(dataset, predictions, probabilities);
        return (Output) {predictions, probabilities};
    }
};
4

1 回答 1

1

这是我想象中的独立测试仪:

住在科利鲁

#include <boost/variant.hpp>
#include <iostream>

struct X;
struct Y;
template <typename... T> struct ClassA {
    void operate(double d, int a, float b) const
    {
        std::cout << __PRETTY_FUNCTION__ << "(" << d << "," << a << "," << b << ")\n";
    }
};

struct Output {
    int   a;
    float b;
};

typedef boost::variant<ClassA<X, Y>, ClassA<>> ClassAGeneric;

class Operation // : public boost::static_visitor<Output>
{
  public:
    double d;
    int    a;
    float  b;

    Output operator()(ClassA<X, Y> const& obj) const
    {
        obj.operate(d, a, b);
        return Output{a, b};
    }

    Output operator()(ClassA<> const& obj) const
    {
        obj.operate(d, a, b);
        return Output{a, b};
    }
};

int main() {
    Operation op {3.14, 42, 9e-2f};


    ClassAGeneric v1 = ClassA<X,Y>{};
    ClassAGeneric v2 = ClassA<>{};
    apply_visitor(op, v1);
    apply_visitor(op, v2);
}

印刷

void ClassA::operate(double, int, float) const with T = {X, Y}
void ClassA::operate(double, int, float) const with T = {}

不出所料,这很有效。现在,一个陷阱可能是当您未能创建operate成员函数const并且参数实际上是const.

另请注意,您可以大大简化访问者(尤其是假设 C++14):Live On Coliru

于 2021-11-16T18:35:20.487 回答