Java动态链接库导出表_如何在动态链接库dll/so中导出自定义的模板类template class...

how to implement a template class with c++ and export in dll/so

Guide

questions

模板类必须在header中实现,而不能在cpp中实现,否则作为dll调用进行链接的时候回出错。

common solutions(Recommend)

implement template functions in header.

ThreadPool.h

class SHARED_EXPORT ThreadPool {

public:

static ThreadPool* Instance(size_t max_thread_pool_size);

~ThreadPool();

// Add new work item to the pool.

template

inline void Enqueue(F f)

{

io_service_.post(f);//sync, return immediately

}

void Free();

private:

static std::shared_ptr m_pInstance;

bool bfree;

ThreadPool(size_t size);

DISABLE_COPY_AND_ASSIGN(ThreadPool);

boost::thread_group workers_;

boost::asio::io_service io_service_;

boost::asio::io_service::work work_;

};

Seperate from headers

solutions 1

A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.

Foo.h

template

struct Foo

{

void doSomething(T param);

};

#include "Foo.cpp" // here

Foo.cpp

template

void Foo::doSomething(T param)

{

//implementation

}

solutions 2

Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:

Foo.h

// no implementation

template struct Foo { ... };

Foo.cpp

#include "Foo.h"

// implementation of Foo's methods

// explicit instantiations

template class Foo;

template class Foo;

// You will only be able to use Foo with int or float

// template void TestClass::templateFunction(int, int);

Reference

History

20191012: created.

Copyright

Post author: kezunlin

Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值