Skip to content

Instantly share code, notes, and snippets.

@Riyaaaaa
Last active June 9, 2016 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Riyaaaaa/32a8db567c99d76b5395e8bf43b7e437 to your computer and use it in GitHub Desktop.
Save Riyaaaaa/32a8db567c99d76b5395e8bf43b7e437 to your computer and use it in GitHub Desktop.
std::bindの中にstd::bindを書くと死ぬ(挙動が変わる) ref: http://qiita.com/Riyaaaa_a/items/ef6cf75a75d2451e5379
Hoge() {
piyo = std::bind(&Hoge::f, this, std::placeholders::_1, protect(std::bind(&Hoge::g, this)));
}
#include <iostream>
#include <functional>
class Hoge {
public:
Hoge() {
piyo = std::bind(&Hoge::f, this, std::placeholders::_1, std::bind(&Hoge::g, this));
}
std::function<void(int)> piyo;
private:
void f(int value, std::function<int()> callback) {
if(callback) {
std::cout << "Called f. Value = " << value + callback() << std::endl;
}
}
int g() {
return 1;
}
};
int main() {
Hoge hoge;
hoge.piyo(10);
return 0;
}
template<typename T>
struct protect_wrapper : T {
protect_wrapper(const T& t) : T(t) {}
protect_wrapper(T&& t) : T(std::move(t)) {}
};
template<typename T, typename U = typename std::decay<T>::type >
typename std::enable_if< !std::is_bind_expression< U >::value, T&& >::type protect(T&& t) {
return std::forward<T>(t);
}
template<typename T, typename U = typename std::decay<T>::type >
typename std::enable_if< std::is_bind_expression< U >::value, protect_wrapper< U > >::type protect(T&& t) {
return protect_wrapper<U>(std::forward<T>(t));
}
Hoge() {
piyo = std::bind(&Hoge::f, this, std::placeholders::_1, protect(std::bind(&Hoge::g, this)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment