C++ 为什么std::bind不能与std::filesystem::path和std::ostream一起工作?
我目前正在尝试编写一个程序,该程序使用C++ 为什么std::bind不能与std::filesystem::path和std::ostream一起工作?,c++,c++11,c++17,stdbind,C++,C++11,C++17,Stdbind,我目前正在尝试编写一个程序,该程序使用std::bind和std::filesystem::path和std::ostream作为参考,如下所示: #include <functional> #include <filesystem> #include <ostream> #include <iostream> struct Buggy{ static void something(const std::filesystem::path
std::bind
和std::filesystem::path
和std::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();
}
#包括
#包括
#包括
#包括
结构车{
静态void something(const std::filesystem::path&path,std::ostream&out);
无效绑定();
};
void-Buggy::bind(){
自动函数=std::bind(&Buggy::something,std::占位符::\u 1,std::cout);
函数(std::filesystem::path(“./”);
}
void bug::something(const std::filesystem::path&path,std::ostream&out){
默认情况下,通过std::bind
绑定的out参数会被复制。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); };
您的理解可能会有所不同,但我总是觉得使用std::bind
很痛苦,因为我们有lambdas,所以我再也没有使用过它