You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化C++17 std::filesystem路径多字符串拼接代码?

简化std::filesystem::path的多段字符串拼接

原代码这种嵌套括号的写法确实繁琐:

std::filesystem::path path = std::filesystem::current_path();
(((path += "str1") += "str2") += "str3");

你想要的path.concat("str1", "str2", "str3")这种可变参数调用完全可以实现,下面是几种实用方案:

方案一:实现全局可变参数拼接函数

利用C++17的折叠表达式,可以轻松写出一个通用的拼接函数,彻底避免嵌套括号:

#include <filesystem>
#include <utility>

namespace fs = std::filesystem;

template<typename Path, typename... Args>
void concat(Path& path, Args&&... args) {
    // 折叠表达式依次拼接每个参数
    (path += std::forward<Args>(args), ...);
}

// 使用示例
int main() {
    fs::path path = fs::current_path();
    concat(path, "str1", "str2", "str3");
}

方案二:自定义路径包装类(成员函数风格)

如果更偏好成员函数的调用方式,可以封装一个继承自std::filesystem::path的类,添加concat成员:

#include <filesystem>
#include <utility>

namespace fs = std::filesystem;

class MyPath : public fs::path {
public:
    // 继承基类的构造函数
    using fs::path::path;

    template<typename... Args>
    MyPath& concat(Args&&... args) {
        (static_cast<fs::path&>(*this) += std::forward<Args>(args), ...);
        return *this;
    }
};

// 使用示例
int main() {
    MyPath path = fs::current_path();
    path.concat("str1", "str2", "str3");
}

额外简化技巧:不用自定义函数也能写得清爽

如果不想额外写函数,也可以用这些方式简化:

  • 利用+=的左结合性,直接去掉多余括号:
    fs::path path = fs::current_path();
    path += "str1" += "str2" += "str3"; // 等价于原写法,但无冗余括号
    
  • 用初始化列表配合范围for循环:
    fs::path path = fs::current_path();
    for (const auto& part : {"str1", "str2", "str3"}) {
        path += part;
    }
    

内容的提问来源于stack exchange,提问作者user3600124

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:12:40