为什么 std::bind 不能与 std::filesystem::path 和 std::ostream 一起使用?

Why wont std::bind work with a std::filesystem::path and std::ostream?

我目前正在尝试编写一个程序,该程序利用 std::bindstd::filesystem::pathstd::ostream,两者都作为参考,如下所示:

#include <functional>
#include <filesystem>
#include <ostream>
#include <iostream>

struct Buggy{
    static void something(const std::filesystem::path &path, std::ostream &out);
    void bind();
};

void Buggy::bind(){
    auto function = std::bind(&Buggy::something, std::placeholders::_1, std::cout);
    function(std::filesystem::path("./"));
}

void Buggy::something(const std::filesystem::path &path, std::ostream &out){
    out << path.string() << std::endl;
}

int main(){
    Buggy buggy;
    buggy.bind();
}

我希望这段代码简单地输出“./”,但相反,它给了我 massive template errors. 这是为什么?我对 std::bind 的使用在我看来是正确的。我正在 Linux.

上使用 g++ --std=c++17 bug4.cpp -o bug4 -lstdc++fs 进行编译

我无法阅读模板错误,因为它们与此标准库的实现细节混杂在一起。我试过用 clang 和 gcc 编译,它们都给出了类似的错误。通过搜索引擎搜索没有给出有用的结果。

通过std::bind绑定的参数默认复制。 std::cout 不可复制。您需要使用 std::ref.

auto function = std::bind(&Buggy::something, std::placeholders::_1, std::ref(std::cout));

就我个人而言,我会避免使用 std::bind 并改用 lambda 表达式。

auto function = [](auto&& path){ return Buggy::something(path, std::cout); };