Maison  >  Questions et réponses  >  le corps du texte

商业的C++模板代码怎么才能不暴露实现?

伊谢尔伦伊谢尔伦2714 Il y a quelques jours555

répondre à tous(3)je répondrai

  • 高洛峰

    高洛峰2017-04-17 13:57:13

    一个不完美的解决办法,显式实例化。
    例如

    templ.h 中

    template <typename T>
    T max (T const& lhs, T const& rhs);

    templ.cpp

    #include "templ.h"
    template <typename T>
    T max (T const& lhs, T const& rhs)
    {
        return lhs > rhs ? lhs : rhs;
    }
    
    int max (int const& lhs, int const& rhs);
    double max (double const& lhs, double const& rhs);
    string max (string const& lhs, string const& rhs);
    //...

    这样cpp中模板被显式实例化后就不会在链接阶段失败,好处是cpp实现不会暴露给客户,只需提供头文件和库文件。
    但局限性在于模板的支持的类型是有限的,用户有新增的类型就不支持了。

    C++98标准有export关键字来实现模板的声明和实现分离。
    即:
    templ.h 中

    export template <typename T>
    T max (T const& lhs, T const& rhs);

    templ.cpp

    #include "templ.h"
    template <typename T>
    T max (T const& lhs, T const& rhs)
    {
        return lhs > rhs ? lhs : rhs;
    }

    但是鲜有编译器实现这个功能,而且C++11标准中export已经没有这个功能了。

    对于模板的实现代码,连微软都是开源的,所以应该是没有啥完美的解决方案了。

    répondre
    0
  • 高洛峰

    高洛峰2017-04-17 13:57:13

    如果只有模板,我认为是不可能的,没见过这种纯模板封装在dll里面的样例,模板不是普通的c++代码。。
    如果自己的算法不想暴露实现,那么唯一的方式就是做成动态库或者静态库以及模板代码两部分,即一部分重要实现搞到库中,不重要的放在模板里面,有点像boost那样子。。

    répondre
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:57:13

    模板基本做不到了,大部分编译器不支持export关键字

    répondre
    0
  • Annulerrépondre