模板是否可以专用于标准库 class 而无需包含 class 的 header?
Can a template be specialized for a standard library class without including that class's header?
假设我正在编写一个特征,我想为所有标准库容器提供 out-of-the-box 专业化。
template <class T>
struct supports_fast_insertion: std::false_type {};
template <class T, class A>
struct supports_fast_insertion<std::list<T, A>>: std::true_type {};
template <class T, class A>
struct supports_fast_insertion<std::forward_list<T, A>>: std::true_type {};
template <class T, class A>
struct supports_fast_insertion<std::unordered_set<T, A>>: std::true_type {};
// ...
这需要 #include <list>
、#include <forward_list>
、#include <unordered_set>
等。这意味着任何包含我的类型特征的文件也将包含容器库的一半,这看起来很草率。
如果我只专注于 user-defined 类型,我可以 forward-declare 所有我关心的类型。但是向 namespace std
添加声明——甚至只是前向声明——invokes undefined behavior.
有没有办法避免#include
爆炸?图书馆有传统的方法来处理这个问题吗?
Is there a way to avoid the #include explosion? Is there a conventional way for libraries to handle this?
遗憾的是,截至撰写本文时,还没有令人满意的答案。如果您希望不惜一切代价避免未定义的行为,那么您必须硬着头皮并包含那些 headers.
如果您知道您的预期实现,并且不介意它是正式的 non-standard,您可以创建一个内部 header(到您的库)在无数编译器下进行转发和库特定的宏检查。 Boost 是执行此操作的库示例,请参阅 boost/detail/container_fwd.hpp
。
假设我正在编写一个特征,我想为所有标准库容器提供 out-of-the-box 专业化。
template <class T>
struct supports_fast_insertion: std::false_type {};
template <class T, class A>
struct supports_fast_insertion<std::list<T, A>>: std::true_type {};
template <class T, class A>
struct supports_fast_insertion<std::forward_list<T, A>>: std::true_type {};
template <class T, class A>
struct supports_fast_insertion<std::unordered_set<T, A>>: std::true_type {};
// ...
这需要 #include <list>
、#include <forward_list>
、#include <unordered_set>
等。这意味着任何包含我的类型特征的文件也将包含容器库的一半,这看起来很草率。
如果我只专注于 user-defined 类型,我可以 forward-declare 所有我关心的类型。但是向 namespace std
添加声明——甚至只是前向声明——invokes undefined behavior.
有没有办法避免#include
爆炸?图书馆有传统的方法来处理这个问题吗?
Is there a way to avoid the #include explosion? Is there a conventional way for libraries to handle this?
遗憾的是,截至撰写本文时,还没有令人满意的答案。如果您希望不惜一切代价避免未定义的行为,那么您必须硬着头皮并包含那些 headers.
如果您知道您的预期实现,并且不介意它是正式的 non-standard,您可以创建一个内部 header(到您的库)在无数编译器下进行转发和库特定的宏检查。 Boost 是执行此操作的库示例,请参阅 boost/detail/container_fwd.hpp
。