以下代码:
#include <boost/variant.hpp>
#include <iostream>
#include <string>
struct A
{
A()
{
}
~A() throw()
{
}
A& operator=(A const & rhs)
{
return *this;
}
bool operator==(A const & rhs)
{
return true;
}
bool operator<(A const & rhs)
{
return false;
}
};
std::ostream & operator<<(std::ostream & os, A const & rhs)
{
os << "A";
return os;
}
typedef boost::variant<int, std::string, A> message_t;
struct dispatcher_t : boost::static_visitor<>
{
template <typename T>
void operator()(T const & t) const
{
std::cout << t << std::endl;
}
};
int main(int argc, char * const * argv)
{
message_t m("hi");
boost::apply_visitor(dispatcher_t(), m);
message_t a(A());
boost::apply_visitor(dispatcher_t(), a);
}
产生以下错误。
In file included from /usr/include/boost/variant/apply_visitor.hpp:17,
from /usr/include/boost/variant.hpp:24,
from main.cpp:2:
/usr/include/boost/variant/detail/apply_visitor_unary.hpp: In function ‘typename Visitor::result_type boost::apply_visitor(const Visitor&, Visitable&) [with Visitor = dispatcher_t, Visitable = message_t(A (*)())]’:
main.cpp:51: instantiated from here
/usr/include/boost/variant/detail/apply_visitor_unary.hpp:72: error: request for member ‘apply_visitor’ in ‘visitable’, which is of non-class type ‘message_t(A (*)())’
/usr/include/boost/variant/detail/apply_visitor_unary.hpp:72: error: return-statement with a value, in function returning 'void'
我最初只是尝试使用一个非常简单的 A,但我试图满足Boost.Variant 对 BoundedTypes的所有要求。A曾经是
struct A {};
访问者使用字符串值可以正常工作,但甚至无法编译访问 A 的尝试。我使用的是 gcc-4.4.5。有任何想法吗?