如何在不包含完整的文件系统头的情况下使用文件系统的类路径C++17?

How to use the class path of filesystem without including the complete filesystem header in C++17?

本文关键字:文件系统 路径 C++17 情况下 包含完      更新时间:2023-10-16

我有两个问题:

第一个问题:

我想创建一个类型的对象

std :: filesystem :: path

我希望在不经过提升的情况下做到这一点,因为标准 C 17 允许这样做。

Boost 的优势在于我们可以做到:

#include <boost / filesystem / path.hpp>

因此,它允许您准确包含所需的内容。

但是如果我一开始就这样做:

#include <filesystem>

那么在这种情况下,它包含了大部分不会被使用的代码(但我不确定这个说法(,在处理后的代码中。

所以,我的第一个问题:是否可以只包含具有C++17标准的文件系统的类"路径"?

我看了:

https://en.cppreference.com/w/cpp/header/filesystem

而且有很多课程我不需要。我只需要"路径"。

如何仅集成路径而不涉及提升?

我想,如果可能的话,在 C 17 中使用 if 文件系统会减少预处理后获得的代码?

谢谢

该标准要求path至少在<filesystem>中向前声明,请参阅:29.11.5 标题<filesystem>概要。实际上,这将取决于您的编译器在哪里声明std::filesystem::path,因此,您应该只包含<filesystem>.

我还觉得,就编译时间而言,只需要包含<boost/filesystem/path.hpp>会比必须包含"所有"<fileysystem>更便宜,但是至少在我的机器上测量它会得到令人惊讶的结果,std::filesystem

$ echo '#include <filesystem>' | time -p g++ -std=c++17 -x c++ -c -
real 0.49
user 0.43
sys 0.05

与仅包括<boost/filesystem/path.hpp>

$ echo '#include <boost/filesystem/path.hpp>' | time -p g++ -std=c++17 -x c++ -c -
real 0.89
user 0.81
sys 0.07

因此,包括<filesystem>几乎是包括"仅"<boost/filesystem/path.hpp>的两倍。为了进一步巩固编译时间的增加可以归因于 Boost 实现而不是其他一些晦涩的原因,我检查了由于分别包含<boost/filesystem/path.hpp><filesystem>而需要预处理的头文件的数量:

$ echo '#include <boost/filesystem/path.hpp>' | g++ -std=c++17 -x c++ -M -c - | wc -l
407

对:

$ echo '#include <filesystem>' | g++ -std=c++17 -x c++ -M -c - | wc -l
144

我认为可以安全地得出结论,如果您担心的是编译时间,您不必担心包含<filesystem>