This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Currently my company has thousands of static / non-static member function pairs, the static function exists purely to call its non-static member function through an instance pointer passed as a member of the parameter. I have been working on a neat templated replacement for all of these static functions, since the parameters are always the same. My solution is a templated static member function that takes a pointer-to-member, and calls it via std::invoke(). However, you do not seem to be able to instantiate the function pointer, through list initialization - but if you cast it or set it directly, it works fine! See the following code and the line that does not compile (commented as such):
#include <iostream>
#include <functional>
struct widget_data;
typedef void(MY_FUNC)(widget_data*);
struct widget_data
{
void* instance;
MY_FUNC* func;
};
template <class CLASSNAME>
class widget_base
{
public:
virtual ~widget_base() {};
static CLASSNAME* get_instance(widget_data* data)
{
return static_cast<CLASSNAME*>(data->instance);
}
template<void(CLASSNAME::*f)(widget_data*)>
static void mem_wrap(widget_data*d)
{
std::invoke(f, get_instance(d), d);
}
};
class widget_derived : public widget_base<widget_derived>
{
private:
widget_data m_widget;
void my_member_func(widget_data*)
{
std::cout << "Hello world" << '\n';
std::cin.get();
};
public:
widget_derived()
{
m_widget.instance = this;
// This works and prints "Hello world"
m_widget.func = mem_wrap<&widget_derived::my_member_func>;
std::invoke(m_widget.func, &m_widget);
// This fails to compile, with "cannot convert from 'void (__cdecl *)(widget_data *)' to 'MY_FUNC (__cdecl *)'"
//m_widget = { this, mem_wrap<&widget_derived::my_member_func> };
// This compiles fine, and prints "Hello world"
m_widget = { this, static_cast<MY_FUNC*>(mem_wrap<&widget_derived::my_member_func>) };
std::invoke(m_widget.func, &m_widget);
}
};
int main(int /*argc*/, char* /*argv*/[])
{
widget_derived();
}
Subreddit
Post Details
- Posted
- 8 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/cpp_questio...