Could somebody please tell me why I am getting compiler error for the last line of the following code?
note: If I remove the following line, my code gets compiled with no error:
appliedEqualityVisitor(compareValue);
Here is the code:
#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;
}
The problem stems from your visitor class. Boost expects a void operator()(...)
, instead you provide an operator()
that returns something.
For your pattern to work, you will have to change the visitor, something like:
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) {}
};
Then test the result. Btw. am not sure that your constructor there to which you pass an int
is safe. You are not holding the reference, rather pointing to a temporary instance of the variant which is constructed from the int - which may be out of scope.
EDIT: I think what you are trying to do is misguided, given that boost::variant
already implements operator==
correctly. For example:
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;
Works fine - and I think it is what you are trying to accomplish? You want to test that two variants are equally comparable(?) This will work as long as all the objects in your variant are equally comparable.