Ошибка компиляции Boost :: bind при попытке установить функцию-член для boost :::: asio :: deadline_timer

У меня небольшая проблема с пониманием ошибок компиляции, которые возникают при попытке создать boost :: asio :: deadline_timer. Я получаю указанные ниже ошибки в следующем примере кода на MSVC10. Он был построен с Boost 1.48

Первая ошибка выглядит так, как будто она жалуется на функцию-член, установленную в качестве обработчика для async_wait, являющейся ссылкой. Однако, когда я меняю аргумент, он дает аналогичную ошибку.

Я смотрел Boost :: Bind и Boost :: Asio, чтобы попытаться понять, что я делаю не так. Мой код похож на этот пример. с тем, как я использую bind и deadline_timer.

Извините за то, насколько беспорядочно выглядят ошибки компиляции. Я все еще пытаюсь разобраться с Markdown.

Пример кода

включают

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

class TimerThing
{
protected:
    boost::asio::deadline_timer* statusTimer_;
    boost::thread_group worker_threads_;

    boost::asio::io_service io_service_;
    boost::shared_ptr<boost::asio::io_service::work> work_;

public:
    TimerThing() {}

    virtual ~TimerThing(){}

    void updateStatus(boost::system::error_code& ec)
    {
        if (ec == boost::asio::error::operation_aborted)
            return;

        std::cout<<"Status Update"<<std::endl;

        statusTimer_->expires_at(statusTimer_->expires_at() + boost::posix_time::seconds(1));
        statusTimer_->async_wait(boost::bind(&TimerThing::updateStatus, this, , boost::asio::placeholders::error));
    }

    void start()
    {
        statusTimer_=new boost::asio::deadline_timer(io_service_);
        boost::shared_ptr<boost::asio::io_service::work> myWork(new boost::asio::io_service::work(io_service_));
        work_=myWork;

        worker_threads_.create_thread( boost::bind( &TimerThing::threadAction, this ) );

        statusTimer_->expires_at(statusTimer_->expires_at() + boost::posix_time::seconds(1));
        statusTimer_->async_wait(boost::bind(&TimerThing::updateStatus, this, boost::asio::placeholders::error));
    }

    void threadAction()
    {
        io_service_.run();
    }

    void stop()
    {
        work_.reset();
        io_service_.stop();
        worker_threads_.join_all();

        delete statusTimer_;
    }

};



#include "TimerThing.h"

int main(int argc, const char* argv[] )
{
    TimerThing t;

    std::string input;
    std::cout<<"Press f to stop"<<std::endl;

    t.start();

    std::cin>>input;

    t.stop();

    return 0;
}

Ошибки компилятора

c: \ Underware \ version \ include \ boost / bind / bind.hpp (313): ошибка C2664: 'R boost :: _ mfi :: mf1 :: operator () (const U &, A1) const': невозможно преобразовать параметр 2 от 'const boost :: system :: error_code' до 'boost :: system :: error_code &'

     with
     [
         R=void,
         T=TimerThing,
         A1=boost::system::error_code &,
         U=TimerThing *
     ]
     Conversion loses qualifiers
     c:\Underware\version\include\boost/bind/bind_template.hpp(47) : see reference to function template instantiation 'void boost::_bi::list2<A1,A2>::operator ()<F,boost::_bi::list1<const boost::system::error_code &>>(boost::_bi::type<T>,F &,A &,int)' being compiled
     with
     [
         A1=boost::_bi::value<TimerThing *>,
         A2=boost::arg<1>,
         F=boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,
         T=void,
         A=boost::_bi::list1<const boost::system::error_code &>
     ]
     c:\Underware\version\include\boost/asio/detail/bind_handler.hpp(46) : see reference to function template instantiation 'void boost::_bi::bind_t<R,F,L>::operator ()<const Arg1>(const A1 &)' being compiled
     with
     [
         R=void,
         F=boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,
         L=boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>,
         Arg1=const boost::system::error_code,
         A1=const boost::system::error_code
     ]

     c:\Underware\version\include\boost/asio/detail/bind_handler.hpp(45) : while compiling class template member function 'void boost::asio::detail::binder1<Handler,Arg1>::operator ()(void)'
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Arg1=boost::system::error_code
     ]
     c:\Underware\version\include\boost/asio/detail/wait_handler.hpp(59) : see reference to class template instantiation 'boost::asio::detail::binder1<Handler,Arg1>' being compiled
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Arg1=boost::system::error_code
     ]

     c:\Underware\version\include\boost/asio/detail/wait_handler.hpp(45) : while compiling class template member function 'void boost::asio::detail::wait_handler<Handler>::do_complete(boost::asio::detail::io_service_impl *,boost::asio::detail::operation *,const boost::system::error_code &,size_t)'
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>
     ]
     c:\Underware\version\include\boost/asio/detail/deadline_timer_service.hpp(185) : see reference to class template instantiation 'boost::asio::detail::wait_handler<Handler>' being compiled
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>
     ]
     c:\Underware\version\include\boost/asio/deadline_timer_service.hpp(137) : see reference to function template instantiation 'void boost::asio::detail::deadline_timer_service<Time_Traits>::async_wait<WaitHandler>(boost::asio::detail::deadline_timer_service<Time_Traits>::implementation_type &,Handler)' being compiled
     with
     [
         Time_Traits=boost::asio::time_traits<boost::posix_time::ptime>,
         WaitHandler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>
     ]
     c:\Underware\version\include\boost/asio/basic_deadline_timer.hpp(502) : see reference to function template instantiation 'void boost::asio::deadline_timer_service<TimeType,TimeTraits>::async_wait<WaitHandler>(boost::asio::detail::deadline_timer_service<Time_Traits>::implementation_type &,const WaitHandler &)' being compiled
     with
     [
         TimeType=boost::posix_time::ptime,
         TimeTraits=boost::asio::time_traits<boost::posix_time::ptime>,
         WaitHandler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Time_Traits=boost::asio::time_traits<boost::posix_time::ptime>
     ]

c: \ users \ tharper \ documents \ visual studio 2010 \ projects \ asiotimer \ asiotimer \ TimerThing.h (48): см. ссылку на создание экземпляра шаблона функции void boost :: asio :: basic_deadline_timer :: async_wait> (const WaitHandler &) 'компилируется

     with
     [
         Time=boost::posix_time::ptime,
         R=void,
         F=boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,
         L=boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>,

WaitHandler = boost :: _ bi :: bind_t, boost :: _ bi :: list2, boost :: arg ‹1> >>
] TimerThing.cpp

c: \ Underware \ version \ include \ boost / bind / bind.hpp (313): ошибка C2664: 'R boost :: _ mfi :: mf1 :: operator () (const U &, A1) const': невозможно преобразовать параметр 2 от 'const boost :: system :: error_code' до 'boost :: system :: error_code &'

     with
     [
         R=void,
         T=TimerThing,
         A1=boost::system::error_code &,
         U=TimerThing *
     ]
     Conversion loses qualifiers

c: \ Underware \ version \ include \ boost / bind / bind_template.hpp (47): см. ссылку на создание экземпляра шаблона функции void boost :: _ bi :: list2 :: operator ()> (boost :: _ bi :: type, F &, A &, int) 'компилируется

     with
     [
         A1=boost::_bi::value<TimerThing *>,
         A2=boost::arg<1>,
         F=boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,
         T=void,
         A=boost::_bi::list1<const boost::system::error_code &>
     ]
     c:\Underware\version\include\boost/asio/detail/bind_handler.hpp(46) : see reference to function template instantiation 'void boost::_bi::bind_t<R,F,L>::operator ()<const Arg1>(const A1 &)' being compiled
     with
     [
         R=void,
         F=boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,
         L=boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<>>,
         Arg1=const boost::system::error_code,
         A1=const boost::system::error_code
     ]
     c:\Underware\version\include\boost/asio/detail/bind_handler.hpp(45) : while compiling class template member function 'void boost::asio::detail::binder1<Handler,Arg1>::operator ()(void)'
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Arg1=boost::system::error_code
     ]
     c:\Underware\version\include\boost/asio/detail/wait_handler.hpp(59) : see reference to class template instantiation 'boost::asio::detail::binder1<Handler,Arg1>' being compiled
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Arg1=boost::system::error_code
     ]
     c:\Underware\version\include\boost/asio/detail/wait_handler.hpp(45) : while compiling class template member function 'void boost::asio::detail::wait_handler<Handler>::do_complete(boost::asio::detail::io_service_impl *,boost::asio::detail::operation *,const boost::system::error_code &,size_t)'
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>
     ]
     c:\Underware\version\include\boost/asio/detail/deadline_timer_service.hpp(185) : see reference to class template instantiation 'boost::asio::detail::wait_handler<Handler>' being compiled
     with
     [
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>
     ]
     c:\Underware\version\include\boost/asio/deadline_timer_service.hpp(137) : see reference to function template instantiation 'void boost::asio::detail::deadline_timer_service<Time_Traits>::async_wait<WaitHandler>(boost::asio::detail::deadline_timer_service<Time_Traits>::implementation_type &,Handler)' being compiled
     with
     [
         Time_Traits=boost::asio::time_traits<boost::posix_time::ptime>,
         WaitHandler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Handler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>
     ]
     c:\Underware\version\include\boost/asio/basic_deadline_timer.hpp(502) : see reference to function template instantiation 'void boost::asio::deadline_timer_service<TimeType,TimeTraits>::async_wait<WaitHandler>(boost::asio::detail::deadline_timer_service<Time_Traits>::implementation_type &,const WaitHandler &)' being compiled
     with
     [
         TimeType=boost::posix_time::ptime,
         TimeTraits=boost::asio::time_traits<boost::posix_time::ptime>,
         WaitHandler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>,
         Time_Traits=boost::asio::time_traits<boost::posix_time::ptime>
     ]
     c:\users\tharper\documents\visual studio 2010\projects\asiotimer\asiotimer\TimerThing.h(48) : see reference to function template instantiation 'void boost::asio::basic_deadline_timer<Time>::async_wait<boost::_bi::bind_t<R,F,L>>(const WaitHandler &)' being compiled
     with
     [
         Time=boost::posix_time::ptime,
         R=void,
         F=boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,
         L=boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>,
         WaitHandler=boost::_bi::bind_t<void,boost::_mfi::mf1<void,TimerThing,boost::system::error_code &>,boost::_bi::list2<boost::_bi::value<TimerThing *>,boost::arg<1>>>
     ]

person Thomas Lann    schedule 18.11.2012    source источник
comment
void updateStatus(boost::system::error_code& ec) должно быть недействительным updateStatus(const boost::system::error_code& ec). И у вас есть лишняя запятая в boost::bind(&TimerThing::updateStatus, this, , boost::asio::placeholders::error));   -  person Igor R.    schedule 21.11.2012
comment
@IgorR. СПАСИБО, СПАСИБО, СПАСИБО, СПАСИБО, СПАСИБО !!! Проблема была в константе. Вы должны превратить комментарий в ответ, чтобы получить кредит.   -  person Thomas Lann    schedule 21.11.2012


Ответы (2)


void updateStatus(boost::system::error_code& ec) должно быть void updateStatus(const boost::system::error_code& ec).

И у вас есть лишняя запятая в boost::bind(&TimerThing::updateStatus, this, , boost::asio::placeholders::error));

person Igor R.    schedule 21.11.2012

Ваша привязка в start верна, а в updateStatus - нет:

void updateStatus(const boost::system::error_code& ec)
{
    if (ec == boost::asio::error::operation_aborted)
        return;

    std::cout<<"Status Update"<<std::endl;

    statusTimer_->expires_at(
      statusTimer_->expires_at() + boost::posix_time::seconds(1));
    statusTimer_->async_wait(
      boost::bind(&TimerThing::updateStatus, this, 
                  boost::asio::placeholders::error));
}

Вам также необходимо использовать заполнитель.

Общий совет: предпочитайте публиковать компилируемые примеры вместо полной панели компилятора. В вашем случае удалите непереносимый мусор VC (tmain, stdafx) и добавьте все включения.

person pmr    schedule 18.11.2012
comment
К сожалению, я все еще получаю ту же ошибку. При устранении проблемы я действительно закомментировал эту строку. Спасибо что подметил это. Это, по крайней мере, сэкономит мне время на устранение неполадок после того, как я решу исходную проблему. Я удалил мусор VC, добавил включения и исправил свое упущение. - person Thomas Lann; 19.11.2012
comment
@ThomasLann gist.github.com/4108222 Этот фрагмент легко компилируется для меня. Ошибка должна быть в части кода, которую вы нам не показываете. - person pmr; 19.11.2012
comment
Собственно, это единственный код. Я считаю, что проблема в том, что я использую библиотеки, созданные кем-то другим. Спасибо за вашу помощь. - person Thomas Lann; 19.11.2012
comment
Я только что скачал свежую копию boost 1.48. У меня сложилось впечатление, что asio не нужно связывать с библиотекой даже из-за ее зависимостей. Это правда? Я использую VS2010, я просто пытался скомпилировать его с этим, и у меня все еще та же проблема. Похоже на настройку компилятора. Можете указать, что вы использовали? - person Thomas Lann; 19.11.2012
comment
В VS Boost используется некоторая магия автоматического связывания. Извините, я не могу вам с этим помочь. Все, что я здесь сделал, это закинул вещи в файл и спел правильные заклинания gcc, включая вызов компоновщика. Если вы уверены, что это проблема компоновщика, опубликуйте новый вопрос и закройте этот. - person pmr; 20.11.2012
comment
Я пожертвовал несколькими чашками кофе и произнес необходимые заклинания, чтобы заставить его работать. Увы, MSVC не выполняет мои приказы. Я не думаю, что это проблема компоновщика, потому что ошибки возникают на этапе компиляции во время сборки. - person Thomas Lann; 20.11.2012