-
-
Save Riyaaaaa/32a8db567c99d76b5395e8bf43b7e437 to your computer and use it in GitHub Desktop.
std::bindの中にstd::bindを書くと死ぬ(挙動が変わる) ref: http://qiita.com/Riyaaaa_a/items/ef6cf75a75d2451e5379
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hoge() { | |
piyo = std::bind(&Hoge::f, this, std::placeholders::_1, protect(std::bind(&Hoge::g, this))); | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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