Coming soon - Get a detailed view of why an account is flagged as spam!
view details

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.

2
Is this a bug in Visual Studio 2015?
Post Flair (click to view more posts with a particular flair)
Post Body

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();
}

Author
Account Strength
90%
Account Age
11 years
Verified Email
Yes
Verified Flair
No
Total Karma
604
Link Karma
38
Comment Karma
566
Profile updated: 3 hours ago
Posts updated: 1 year ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
8 years ago