为什么我不能使用boost :: variant访问此自定义类型?

时间:2011-04-20 23:33:19

标签: c++ visitor boost-variant

以下代码:

#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上。以前是

struct A {};

访问者使用字符串值工作正常,但甚至无法编译访问A的尝试。我正在使用gcc-4.4.5。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

message_t a(A());

具有最令人烦恼的解析问题:声明一个函数而不是创建一个变量。许多解决方法,例如message_t a = A();