Member function pointer wrapper using variadic template

爱⌒轻易说出口 提交于 2019-12-11 10:35:44

问题


I'm currently trying to compile my code using Visual C++ 2013 and want to take the advantage of variadic templates. I have several classes which wrap the function pointer - several versions for different number of arguments.

The wrapper for a member function with one argument is the following:

template <typename T, T> struct proxy;

template <typename T, typename R, typename Arg0, R(T::*mf)(Arg0)>
struct proxy<R(T::*)(Arg0), mf>
{
    proxy(T& host) : m_Host(host) {}

    template <typename Arg0>
    R call(Arg0&& arg0)
    {
        return (m_Host.*mf)(std::forward<Arg0>(arg0));
    }

private:
    proxy& operator=(const proxy&);
    T& m_Host;
};

Let's have some test class:

class SomeHost
{
public:
    int SomeGetter() { return 42; }
    void SomeSetter(int var) { m_Var = var;}
private:
    int m_Var;
};

and a test case:

void test()
{
    SomeHost obj;
    proxy<void(SomeHost::*)(int), &SomeHost::SomeSetter> g(obj);
    g.call(5);
}

Everything works fine so far. I rewrote the proxy class using variadic template:

template <typename T, typename R, typename... Args, R(T::*mf)(Args...)>
struct proxy<R(T::*)(Args...), mf>
{
    proxy(T& host) : m_Host(host) {}

    template <typename... Args>
    R call(Args&&... args)
    {
        return (m_Host.*mf)(std::forward<Args>(args)...);
    }

private:
    proxy& operator=(const proxy&);
    T& m_Host;
};

Using the variadic template, Visual C++ 2013 shows me several compiler errors coming from the test function:

file.cpp(79): error C2440: 'specialization' : cannot convert from 'overloaded-function' to 'void (__thiscall SomeHost::* )(void)'
1> None of the functions with this name in scope match the target type: see reference to class template instantiation 'proxy<void (__thiscall SomeHost::* )(int),SomeHost::SomeSetter>' being compiled
1>file.cpp(79): error C2973: 'proxy<R(__thiscall T::* )(Args...),mf>' : invalid template argument 'overloaded-function'
1>file.cpp(40) : see declaration of 'proxy<R(__thiscall T::* )(Args...),mf>'

I also tested the template with the SomeHost::SomeGetter() and it worked without any problems.

Any help is highly appreciated.

Thanks a lot...

来源:https://stackoverflow.com/questions/24283072/member-function-pointer-wrapper-using-variadic-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!