gpt4 book ai didi

c++ - 使用 'include wrapper' 是否被认为是不良做法/指示不良设计?

转载 作者:行者123 更新时间:2023-11-28 07:46:06 27 4
gpt4 key购买 nike

考虑这样一种情况,您的任务是为标准库容器编写一个简单的 pretty-print 工具。在 header 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.

但是,由于容器不能向前声明,您必须为每个容器 header 设置 #include。因此,将 pretty_print.hpp 包含到库的其他部分会(可能?)导致大量代码膨胀。因此,为了避免将这些依赖项引入其他编译单元,您制作了一堆文件(我称它们为“ header 包装器”,因为我找不到任何其他术语)称为 print_vector.hppprint_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 一个 vector 时,您需要 #include print_vector.hpp 并且它只会将 <vector> 引入当前编译单元,而不是 <set><map> 或您可能不需要的任何其他 header 。请注意,我以 pretty_print 为例(我确信有更好的方法来制作 pretty-print 容器)但是您可能还有其他原因想要这样做(例如制作一个 lean_windows.h header “包装器”,其中您之前使用 #define WIN32_LEAN_AND_MEAN包括 windows.h )。

我看不出这种方法有什么问题,因为这意味着您避免了由于引入一堆您可能不会在编译单元中使用/不需要的 header 而导致的潜在膨胀。尽管如此,它仍然感觉“错误”,因为它可能对其他人来说并不明显,你的“包含包装器”实际上包含了你想要的 header ,并且似乎玷污了包含标准库 header 的“神圣性”( #include <string> 是惯用的,而 #include "string_wrapper.hpp" 不是)。

这是否被认为是不良做法\指示不良设计?

最佳答案

一些图书馆处理这类事情的一种方法是让用户决定。制作像 print/vector.hppprint/set.hpp 这样的文件,也制作像 print/all.hpp 这样的文件(或者只是 print.hpp,尽管这可能会助长坏习惯)。最后一个文件只是 #include 所有单独的文件,所以想要“方便”的人可以拥有它,而想要精简编译的人也可以拥有它。

一个与上述类似的常见示例是 Boost 的智能指针库:http://www.boost.org/doc/libs/release/boost/smart_ptr.hpp

关于c++ - 使用 'include wrapper' 是否被认为是不良做法/指示不良设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14853079/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com