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

joh*_*dav 0 c++ stdbind c++11 c++17

我目前正在尝试编写一个程序,该程序使用std::binda std::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();
}
Run Code Online (Sandbox Code Playgroud)

我希望这段代码只输出" ./",但相反,它给了我大量的模板错误.为什么是这样?我对std::bind外观的使用对我来说是正确的.我g++ --std=c++17 bug4.cpp -o bug4 -lstdc++fs在Linux上编译.

我无法读取模板错误,因为它们与此标准库的实现细节混杂在一起.我尝试使用clang和gcc进行编译,两者都会产生类似的错误.通过搜索引擎搜索没有给出有用的结果.

mil*_*bug 9

std::bind默认情况下会复制绑定的参数.std::cout是不可复制的.你需要使用std::ref.

auto function = std::bind(&Buggy::something, std::placeholders::_1, std::ref(std::cout));
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会避免使用std::bind和使用lambda表达式.

auto function = [](auto&& path){ return Buggy::something(path, std::cout); };
Run Code Online (Sandbox Code Playgroud)