如何在動態連接庫dll/so中導出自定義的模板類template class | how to implement a template class with c++ and export in dl

本文首發於我的博客kezunlin.me/post/4ec4ae…,歡迎閱讀最新內容!html

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

Guide

questions

模板類必須在header中實現,而不能在cpp中實現,不然做爲dll調用進行連接的時候回出錯。less

common solutions(Recommend)

implement template functions in header.ide

ThreadPool.hpost

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.ui

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:this

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

  • 20191012: created.

Copyright

相關文章
相關標籤/搜索