如何使用 std::bind with compose2.
How to use std::bind with compose2?
我想在 C++11 的compose2
中使用binary_function
,而不使用boost
库std::bind
。
编辑:或拉布达斯。
假设我有以下定义:
bool GreaterThanFive(int x) { return x > 5; }
struct DivisibleByN : binary_function<int, int, bool> {
bool operator()(int x, int n) const { return x % n == 0; }
};
假设我想计算一个向量的元素,这些元素大于 5 且能被 3 整除。我可以轻松地将它们与以下内容相结合:
int NumBothCriteria(std::vector<int> v) {
return std::count_if(v.begin(), v.end(),
__gnu_cxx::compose2(std::logical_and<bool>(),
std::bind2nd(DivisibleByN(), 3),
std::ref(GreaterThanFive)));
}
由于bind2nd
在 C++11 年已弃用,我想移至 std::bind
.我还没有弄清楚为什么以下内容不等效(并且不编译(。
int NumBothCriteria(std::vector<int> v) {
using namespace std::placeholders;
return std::count_if(v.begin(), v.end(),
__gnu_cxx::compose2(std::logical_and<bool>(),
std::bind(DivisibleByN(), _1, 3),
std::ref(GreaterThanFive)));
}
它给了我以下编译错误:
no type named 'argument_type' in 'std::_Bind<DivisibleByN *(std::_Placeholder<1>, int)>`
operator()(const typename _Operation2::argument_type& __x) const
~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
我的直觉是,std::bind
没有做std::bind2nd
做的事情,但我不确定如何让argument_type
typedef恢复。
我的搜索提出了三个问题。第一个使用bind2nd
,第二个使用boost
,第三个用于C++03。不幸的是,有效的STL仍然使用std::bind2nd
。
只是不要使用bind
或compose2
。你以后会感谢自己:
int NumBothCriteria(std::vector<int> v) {
return std::count_if(v.begin(), v.end(),
[](int i){ return i > 5 && i%3 == 0; });
}
<小时 />您正在寻找的答案是,您可以简单地使用std::bind
代替您使用__gnu_cxx::compose2
的位置:
return std::count_if(v.begin(), v.end(),
std::bind(std::logical_and<bool>(),
std::bind(DivisibleByN(), _1, 3),
std::bind(GreaterThanFive, _1)));
但这比仅仅使用 lambda 要复杂得多,也更难推理。
我想出了如何让它与std::function
一起工作。
int NumBothCriteria2(std::vector<int> v) {
using std::placeholders::_1;
return std::count_if(v.begin(), v.end(),
__gnu_cxx::compose2(std::logical_and<bool>(),
std::function<int(int)>(std::bind(
DivisibleByN(), _1, 3)),
std::ref(GreaterThanFive)));
}
相关文章:
- Problems with std::cin.fail()
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- Boost.TEST with CLion: "Test framework quit unexpectedly"
- 避免碎片化的ClientHellos with OpenSSL (DTLS)
- Issues with Win32 ReadProcessMemory API
- Qt with WinAPI MouseProc
- [[maybe_unused]] with structured_binding?
- Issue with WriteProcessMemory
- OpenCV RTP-Stream with FFMPEG
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- std::adjacent_difference with std::chrono time_point
- DLL Made with CMake 使程序崩溃
- QtCreator with C 库中的链接器问题
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- specialized std::default_delete with QQmlComponent
- VS2019 - Sudo Remote Debugging on Linux with Cmake project
- Inference pytorch C++ with alexnet and cv::imread image
- Pybind11: init<> with lambda
- 如何使用 std::bind with compose2.