How to import/export C++ template classes

时间:2018-02-03 10:45:09

标签: c++ templates dll

How can I use and consume a template class when it is compiled in a shared library and a static library?

For example, I have a library project:

/// Lib/Config.hpp
// if building a shared library
#ifdef LIB_BUILD_DLL
#  define LIB_API          __declspec(dllexport)
#  define LIB_TEMPLATE_API __declspec(dllexport)
#  define LIB_EXTERN
// exe projects use the shared library
#elif defined(LIB_DLL)
#  define LIB_API          __declspec(dllimport)
#  define LIB_TEMPLATE_API
#  define LIB_EXTERN       extern
// if building a static library, and exe projects use the static library
#else
#  define LIB_API
#  define LIB_TEMPLATE_API
#  define LIB_EXTERN
#endif
/// End of Lib/Config.hpp

/// Lib/Location.hpp
template<typename T>
LIB_EXTERN class Vector2;

class LIB_API Location
{
public:
     Vector2<float> point;
};
/// End of Lib/Location.hpp

/// Lib/Vector2.hpp
template<typename T>
LIB_EXTERN class LIB_TEMPLATE_API Vector2
{
public:
    template <typename U>
    explicit Vector2(const Vector2<U>& vector)
    {
        x = vector.x;
        y = vector.y;
    }

    Vector2<T> operator -(const Vector2<T>& right)
    {
        return Vector2<T>(x - right.x, y - right.y);
    }

    T x;
    T y;
};
typedef Vector2<float> Vector2f;
/// End of Lib/Vector2.hpp

And a exe main project:

#include "Lib/Config.hpp"
#include "Lib/Location.hpp"
#include "Lib/Vector2.hpp"

class Application
{
public:
    Location location_;
    Vector2<float> point_;
    Vector2f float_point_;
}

What I'd like to ask is if I correctly use LIB_EXTERN the right way?

And how can I pass a Vector2f object to a copy constructor Vector2(const Vector2<U>& vector)?

1 个答案:

答案 0 :(得分:0)

您通常不会导出模板函数或类。它们是为每个翻译单元编译的,并在必要时由链接器清理。只需包含.hpp文件就可以在需要的地方编译必要的代码。

相关问题