3

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?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Ken Smith
  • 775
  • 5
  • 11

1 Answers1

4
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();

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • Does this parse issue have anything to do with boost::variant having a templated conversion constructor for its bounded types? – Ken Smith Apr 21 '11 at 16:46
  • @Ken: no - it has nothing to do with `boost::variant` at all. For *any* types `T` and `U`, a statement of the form `T a(U());` will be considered a declaration of a function called `a`, returning a `T`, taking a `U` parameter. – Tony Delroy Apr 22 '11 at 01:16