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

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

本文首发于个人博客https://kezunlin.me/post/4ec4ae49/,欢迎阅读最新内容!

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

<!--more-->

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<class F> 
	inline void Enqueue(F f)
	{
		io_service_.post(f);//sync, return immediately
	}

	void Free();

private:
	static std::shared_ptr<ThreadPool> 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 <typename T>
struct Foo
{
    void doSomething(T param);
};

#include "Foo.cpp" // here

Foo.cpp

template <typename T>
void Foo<T>::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 <typename T> struct Foo { ... };

Foo.cpp

#include "Foo.h"

// implementation of Foo's methods

// explicit instantiations
template class Foo<int>;
template class Foo<float>;
// You will only be able to use Foo with int or float

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

Reference

History

Copyright

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看