Почему я не могу посетить этот пользовательский тип с помощью 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. Любые идеи?


person Ken Smith    schedule 20.04.2011    source источник


Ответы (1)


message_t a(A());

Имеет самую неприятную проблему синтаксического анализа: объявляет функцию, а не создает переменную. Многие способы решения, например. message_t a = A();

person Tony Delroy    schedule 21.04.2011
comment
Имеет ли эта проблема анализа какое-либо отношение к тому, что boost::variant имеет шаблонный конструктор преобразования для своих ограниченных типов? - person Ken Smith; 21.04.2011
comment
@Ken: нет, это вообще не имеет ничего общего с boost::variant. Для любых типов T и U оператор формы T a(U()); будет считаться объявлением функции с именем a, возвращающей T и принимающей параметр U. - person Tony Delroy; 22.04.2011
comment
Корявый. Благодарю за разъяснение. - person Ken Smith; 22.04.2011