I figured I could initialize a type that takes a callable with std::bind to a member function at top level. However, I seem to make a mistake. I just can't point my fingers where. Compiler errors seem pretty arbitrary...
#include <functional>
#include <type_traits>
#include <cstdio>
template <typename Callable>
struct timer
{
template <typename = std::enable_if_t<std::is_invocable_v<Callable>, void>>
timer(Callable func)
: func_ {func}
{
}
void invoke() const {
func_();
}
Callable func_;
};
struct some_struct
{
void do_something() {
timer_.invoke();
}
void request() {
printf("Hello\n");
}
const timer<decltype(std::bind(&some_struct::request, some_struct*))> timer_ { std::bind(&some_struct::request, this) };
};
int main()
{
some_struct obj;
obj.do_something();
}
EDIT: Here's the errors (gcc 12.2):
<source>:31:70: error: expected primary-expression before '*' token
31 | const timer<decltype(std::bind(&some_struct::request, some_struct*))> timer_ { std::bind(&some_struct::request, this) };
| ^
<source>:31:71: error: expected primary-expression before ')' token
31 | const timer<decltype(std::bind(&some_struct::request, some_struct*))> timer_ { std::bind(&some_struct::request, this) };
| ^
<source>:31:73: error: template argument 1 is invalid
31 | const timer<decltype(std::bind(&some_struct::request, some_struct*))> timer_ { std::bind(&some_struct::request, this) };
| ^
<source>:31:123: error: cannot convert '<brace-enclosed initializer list>' to 'const int' in initialization
31 | const timer<decltype(std::bind(&some_struct::request, some_struct*))> timer_ { std::bind(&some_struct::request, this) };
| ^
<source>: In member function 'void some_struct::do_something()':
<source>:24:16: error: request for member 'invoke' in '((some_struct*)this)->some_struct::timer_', which is of non-class type 'const int'
24 | timer_.invoke();
|
^~~~~~