处理聊天我想使用回调作为将消息从特定客户端的流“传输”到服务器的方式,服务器稍后应该将该消息发送给其他客户端。
以下是该功能的代码:
void Server::waitForConnection(){
Connection::pointer connect = Connection::create(accept.get_io_service());
accept.async_accept(connect->getSocket(), boost::bind(&Server::acceptConnection, this, connect, boost::asio::placeholders::error));
}
void Server::acceptConnection(Connection::pointer connection, const boost::system::error_code& error){
if (!error)
{
connections.push_back(connection);
connection->readMsg(boost::bind(&Server::msgHandler,this, boost::placeholders::_1));
}
else
{
std::cout << "Server::acceptConnection error" << std::endl;
}
waitForConnection();
}
-
template<typename T> void Connection::readMsg(T msgHandler){
const char delim = '\n';
//boost::asio::async_read_until(soc, boost::asio::buffer(arr), delim);
std::string tmp;
do{
boost::asio::read_until(soc, buf, delim);
std::istream is(&buf);
std::getline(is,tmp);
msgHandler(tmp);
} while (tmp != "leave");
}
编译后,我收到以下错误:
Server.obj:错误LNK2019:未解析的外部符号“public:void __thiscall Connection :: readMsg,class std :: allocator&gt;&gt ;, class boost :: _ bi :: list2,struct boost :: arg&lt; 1&gt; &gt;&gt;&gt;(类boost :: _ bi :: bind_t,类std :: allocator&gt;&gt;,类boost :: _ bi :: list2,struct boost :: arg&lt; 1&gt;&gt;&gt;)“( ?? $ readMsg @ V'$ bind_t @ XV?$ MF1 @ @@ XVServer V'$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@@ _ MFI @升压@@ V'$ @列表2 V'$ @值@@@ PAVServer _双@升压@@ U&$ @ ARG 00 $ @ 3 @@ _双@ 3 @@ _双@提升@@@连接@@ QAEXV?$ @ bind_t第十五?$ @ MF1 @@ XVServer V'$ @的basic_string杜?$ @ char_traits @ d @@性病V'$ @分配器@ d @@ 2 STD @@@ _ MFI @提振@@ V'$ @列表2 V'$ value @ PAVServer @@@ _ bi @ boost @@ U?$ arg @ $ 00 @ 3 @@ _ bi @ 3 @@ _ bi @ boost @@@ Z)在函数“private:void __thiscall Server :: acceptConnection(class boost: :shared_ptr,类boost :: system :: error_code const&amp;)“(?acceptConnection @ Server @@ AAEXV?$ shared_ptr @ VConnection @@@ boost @@ ABVerror_code @ system @ 3 @@ Z)
这是我用来尝试重新创建问题的最小,可编译的代码:
#include <iostream>
#include <boost/bind.hpp>
#include <cmath>
using namespace std;
class A;
class B;
class C;
class C{
public:
template <typename T>void init(T t);
};
class B{
public:
template <typename T>void init(T t);
void what(string s);
};
void B::what(string s){
cout << "in what " << s.c_str() << endl;
}
class A{
B obj;
int id;
public:
void init();
void func(string s);
};
void A::func(string s){
cout << s.c_str() << " yes " <<id<< endl;
}
void A::init(){
id = rand()%1024;
obj.init(boost::bind(&A::func, this, boost::placeholders::_1));
}
template <typename T>void B::init(T t){
//A a;
//(a.*t)();
C c;
c.init(boost::bind(&B::what, this, boost::placeholders::_1));
t("from B");
}
template <typename T>void C::init(T t){
//A a;
//(a.*t)();
t("from C");
}
int main(){
A a;
a.init();
a.func("main");
system("pause");
}
然而,它无法达到其目的,这使我转向SO并询问实际上可能导致链接器错误的原因。
完整代码:
Connection.cpp
Connection.h
Server.cpp
Server.h
main.cpp