gpt4 book ai didi

c++ - boost :将变体与 apply_visitor 进行比较

转载 作者:行者123 更新时间:2023-11-28 07:53:25 26 4
gpt4 key购买 nike

有人能告诉我为什么我在以下代码的最后一行遇到编译器错误吗?

注意:如果我删除以下行,我的代码将无错误地编译:

appliedEqualityVisitor(compareValue);

代码如下:

#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"

using namespace std;
using namespace boost;


template<typename T>
struct CheckOneTypeEquality : public boost::static_visitor<>
{
T const* value;
bool operator()( T const& other ) const
{
return other == *value;
}
template<typename U>
bool operator()( U const& other ) const
{
return false;
}
CheckOneTypeEquality( T const& value_ ):value(&value_) {}
};

typedef variant<int, string> MyVariant;
typedef apply_visitor_delayed_t<CheckOneTypeEquality<MyVariant>> AppliedEqualityVisitorType;

int main(int argc, char **argv)
{
int testValue = 12;
CheckOneTypeEquality<MyVariant> equalityVisitor(testValue);

AppliedEqualityVisitorType appliedEqualityVisitor = apply_visitor(equalityVisitor);

MyVariant compareValue = 13;
appliedEqualityVisitor(compareValue); // <<<<< compile error here

return 0;
}

最佳答案

问题源于您的访问者类。 Boost 需要一个 void operator()(...),而您提供了一个返回某些内容的 operator()

要使您的模式生效,您必须更改访问者,例如:

template<typename T>
struct CheckOneTypeEquality : public boost::static_visitor<>
{
T const* value;
mutable bool check;
void operator()( T const& other ) const
{
check = other == *value;
}
template<typename U>
void operator()( U const& other ) const
{
check = false;
}
CheckOneTypeEquality( T const& value_ ):value(&value_), check(false) {}
};

然后测试结果。顺便提一句。我不确定您向其传递 int 的构造函数是否安全。您没有持有引用,而是指向变体的一个临时实例,它是从 int 构造的 - 这可能超出范围。

编辑:鉴于 boost::variant 已经正确实现了 operator==,我认为您尝试做的事情是错误的。例如:

MyVariant testValue = 12;

MyVariant compareValue = 13;
MyVariant compareValue2 = 12;
MyVariant compareValue3 = "12";

std::cout << (compareValue == testValue) << std::endl;
std::cout << (compareValue2 == testValue) << std::endl;
std::cout << (compareValue3 == testValue) << std::endl;

工作正常 - 我认为这就是您想要完成的目标?你想测试两个变体是否具有同等可比性(?)只要你的变体中的所有对象都具有同等可比性,这就可以工作。

关于c++ - boost :将变体与 apply_visitor 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com