尝试使用 boost::variant 时出错 - "No matching function for call"

Error while trying to use the boost::variant - "No matching function for call"

我在使用 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};
    }
};

我在 obj.operate() 中的 first operator() 调用中收到此错误.

我试过像其他答案中提到的那样传递模板,但我仍然看到错误。

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};
    }
};

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

Live On Coliru

#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