Why can't I visit this custom type with boost::variant?

雨燕双飞 提交于 2019-12-01 06:20:41

问题


The following code:

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

Yields the following error.

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'

I originally just tried using a very simple A but I was trying to satisfy every requirement Boost.Variant places on BoundedTypes. A used to be

struct A {};

The visitor works fine with the string value but can't even compile the attempt to visit A. I'm using gcc-4.4.5. Any ideas?


回答1:


message_t a(A());

Has the most-vexing-parse problem: declares a function rather than creates a variable. Many ways to resolve, e.g. message_t a = A();



来源:https://stackoverflow.com/questions/5737826/why-cant-i-visit-this-custom-type-with-boostvariant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!