C++:使用模板和提升::绑定的链接器问题

C++: Linker issue using template and boost::bind

本文关键字:绑定 链接 问题 C++      更新时间:2023-10-16

我正在尝试编写一个名为"Timer"的类,它环绕boost::asio::d eadline_timer,并增加了使每个deadline_timer在自己的线程中运行的功能(彼此独立)。

不幸的是,我无法使用boost::bind 调用我在自己的类中定义的typedef(以下内容将使我的问题更加清晰)。

在我的"Timer"类中,我的 asyncWait() 的签名如下(并调用 deadline_timer.async_wait()):

template <typename WaitHandler>
void Timer::asyncWait(WaitHandler handler) { ... }

我正在尝试从"服务器"类的方法中调用此方法,如下所示:

boost::scoped_ptr<Timer> mButton;
// some code
mButton->asyncWait(boost::bind(&Server::foo, this, boost::asio::placeholders::error));

使用方法:

void Server::foo(const boost::system::error_code& error) { ... }

但是在链接器期间现在出现以下错误,我不明白:

error: undefined reference to 'void Timer::asyncWait<boost::_bi::bind_t<void, boost::_mfi::mf1<void, Server, boost::system::error_code const&>, boost::_bi::list2<boost::_bi::value<Server*>, boost::arg<1> (*)()> > >(boost::_bi::bind_t<void, boost::_mfi::mf1<void, Server, boost::system::error_code const&>, boost::_bi::list2<boost::_bi::value<Server*>, boost::arg<1> (*)()> >)'
collect2: ld returned 1 exit status

这被打印用于在服务器方法中调用 mButton->asyncWait()。我不明白它为什么要编译,但它无法链接。类"Timer"作为共享库添加到编译中,因此它似乎不是这里的实际问题。请问可能有什么问题,我该如何解决?

最有可能的是,asynchWait() 的实现在您实例化函数模板的位置不可见。确保在使用该函数时,该实现对编译器可见,例如,通过在声明函数的同一标头中实现该函数。

说明:通常,编译器只为模板函数生成机器代码。对于模板函数,编译器将机器代码的生成推迟到模板实例化的实际类型已知的点。这是因为它可以使不同类型产生巨大的差异。取两个整数之和的代码很可能与对两个容器或向量求和的代码有很大不同。