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

查看:248
本文介绍了商业的C++模板代码怎么才能不暴露实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

比如公司写了一个商业的C++库要卖给客户,是模板类和模板函数,但不想暴露实现,这能做到呢?

解决方案

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

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已经没有这个功能了。

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

这篇关于商业的C++模板代码怎么才能不暴露实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆