template function pointer parameter in a class met

2019-08-28 03:21发布

I have a class method which takes in a function pointer of an object of any class but with a specific return and parameter list.
The problem is that the compiler returns that what I pass is not the same as the arguments of the method I'm using.
There are other things I'm have trouble with but I will point them out below and as always not every detail is here only whatever is important.

Class.h:

template<typename Value, typename ...Args>

class thing <Value(Args...)> 
{
    /* moar code */
    template<typename C> 
    void method(C* object, Value(C::*func)(Args...), Args... /*how do I pass all of the parameters from here*/) 
    {
        (object->*fund)(/*then put the parameters in here*/);
        /* Also would this work with or with out parameters being passed*/
        /* this is then wrapped and stored to be used later */
    }
}

In main func:

thing<void(int)> thingObj;
AClass obj(/*initialise if needed*/);
thingObj.method(&obj, &AClass::func, /*Parameters*/);

Reason for not using boost/std::function is this is an experiment so I can lean how this works
Excuse the typos and lack of formatting on phone, will correct things and add detail wherever I feel necessary

2条回答
倾城 Initia
2楼-- · 2019-08-28 03:46

You can use indices for it.

template<std::size_t...> struct seq{};

template<std::size_t N, std::size_t... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};

template<std::size_t... Is>
struct gen_seq<0, Is...> : seq<Is...>{};

Then write overloading of your method like this

template<typename C, size_t... indices>
void method(C* object, Value(C::*func)(Args...),
std::tuple<Args...>&& args, seq<indices...>)
{
   (object->*func)(std::get<indices>(args)...);
}

And call it in your first method like

method(object, func, std::forward_as_tuple(args...), gen_seq<sizeof...(Args)>{});

Live example

查看更多
Melony?
3楼-- · 2019-08-28 03:51

This works for me:

#include <iostream>

template <typename Signature>
class thing;

template <typename Value, typename... Args>
class thing <Value(Args...)> 
{
public:
    template<typename C> 
    void method(C* object, Value(C::*func)(Args...) const, Args&&... args) 
    {
        (object->*func)(std::forward<Args>(args)...);
    }
};

struct AClass
{
    void func(int i) const
    {
        std::cout << "passed " << i << std::endl;
    }
};

struct BClass
{
    void add(double a, double b) const
    {
        std::cout << a << " + " << b << " = " << a + b << std::endl;
    }
};

int main()
{
    thing<void(int)> thingObj;
    AClass obj;

    thingObj.method(&obj, &AClass::func, 5);

    BClass bobj;
    thing<void(double, double)> anotherThing;

    anotherThing.method(&bobj, &BClass::add, 10.2, 11);
}
查看更多
登录 后发表回答