Created
June 28, 2020 06:51
-
-
Save mrk21/a971321c3129ee45fba82c1ed57b0cfb to your computer and use it in GitHub Desktop.
Convert function object to function pointer (C++) - https://www.it-swarm.dev/ja/c++/%E9%96%A2%E6%95%B0%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%81%A8%E3%81%97%E3%81%A6%E3%82%AD%E3%83%A3%E3%83%83%E3%83%97%E3%83%81%E3%83%A3%E3%83%A9%E3%83%A0%E3%83%80%E3%82%92%E6%B8%A1%E3%82%8B/1050830580/
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<type_traits> | |
#include<utility> | |
#include<iostream> | |
template<typename Callable> | |
union storage | |
{ | |
storage() {} | |
std::decay_t<Callable> callable; | |
}; | |
template<int, typename Callable, typename Ret, typename... Args> | |
auto fnptr_(Callable&& c, Ret (*)(Args...)) | |
{ | |
static bool used = false; | |
static storage<Callable> s; | |
using type = decltype(s.callable); | |
if(used) | |
s.callable.~type(); | |
new (&s.callable) type(std::forward<Callable>(c)); | |
used = true; | |
return [](Args... args) -> Ret { | |
return Ret(s.callable(std::forward<Args>(args)...)); | |
}; | |
} | |
template<typename Fn, int N = 0, typename Callable> | |
Fn* fnptr(Callable&& c) | |
{ | |
return fnptr_<N>(std::forward<Callable>(c), (Fn*)nullptr); | |
} | |
void foo(void (*fn)()) | |
{ | |
fn(); | |
} | |
int main() | |
{ | |
int i = 42; | |
auto fn = fnptr<void()>([i]{std::cout << i;}); | |
foo(fn); // compiles! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment