考虑一种情况,您的任务是为标准库容器编写一个简单的漂亮打印工具。在标题pretty_print.hpp
中声明以下函数:
// In pretty_print.hpp
template<typename T>
void pretty_print(std::ostream& os, std::vector<T> const& vec);
template<typename T>
void pretty_print(std::ostream& os, std::set<T> const& set);
template<typename T, typename U>
void pretty_print(std::ostream& os, std::map<T, U> const& map);
// etc.
但是,由于无法前向声明容器,因此您必须#include
使用每个容器标头。结果,包含pretty_print.hpp
到库的其他部分会(可能?)导致大量代码膨胀。因此,为了避免将这些依赖项引入其他编译单元,您制作了一堆文件(我称它们为“头文件包装器”,因为我找不到任何其他术语)print_vector.hpp
,print_set.hpp
它们都有一个类似的布局:
// In print_vector.hpp
#include <vector>
template<typename T>
void pretty_print(std::ostream& os, std::vector<T> const& vec);
// In print_set.hpp
#include <set>
template<typename T>
void pretty_print(std::ostream& os, std::set<T> const& set);
// you get the point
因此,当您希望能够pretty_print
使用向量时,您会#include print_vector.hpp
并且它只会引入<vector>
当前编译单元而不是<set>
,<map>
或您可能不需要的任何其他标头。请注意,我正在使用pretty_print
作为示例(我确信有很多更好的方法可以漂亮地打印容器),但您可能还有其他原因想要这样做(例如,在include之前在其中创建lean_windows.h
标题“包装器” )。#define WIN32_LEAN_AND_MEAN
windows.h
我看不出这种方法有什么问题,因为这意味着您避免了在编译单元中引入一堆您可能不需要/不需要的头文件而导致的潜在膨胀。尽管如此,它仍然感觉“错误”,因为其他人可能看不到您的“包含包装器”实际上包含您想要的标头,并且似乎玷污了包含标准库标头的“神圣性”(#include <string>
是惯用的,而#include "string_wrapper.hpp"
不是)。
这是否被认为是不好的做法\表明设计不好?