c++ - 类方法中的模板函数指针参数

标签 c++ class function-pointers

我有一个类方法,它接收任何类对象的函数指针,但具有特定的返回值和参数列表。
问题是编译器返回我传递的内容与我正在使用的方法的参数不同。
还有其他一些事情我遇到了麻烦,但我会在下面指出它们,而且一如既往,这里并不是每个细节都只有重要的。

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 */
    }
}

在主函数中:

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

不使用 boost/std::function 的原因是这是一个实验,所以我可以了解它是如何工作的
请原谅手机上的拼写错误和格式不全,我会更正内容并在我认为有必要的地方添加细节

最佳答案

这对我有用:

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

关于c++ - 类方法中的模板函数指针参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27423913/

相关文章:

c++ - 用于编写 GUI 的通用语言 (C++)

C++,在指针上使用 [] 符号?

c++ - 在继承中使用 delete 的意外行为,基指针对象指向最派生的类

python - 为什么类的主体在定义时执行?

c++ - 将 void (*)() 转换为 void (*)(unsigned char)

c++:无法理解消息处理程序

c++ - 将内置类型转换为 vector<char>

c++ - C++ 和 OpenGL 矩阵顺序之间的混淆(行优先与列优先)

c++ - 表达式未计算为常量 - 使用另一个类中的常量

c - c中的pf apply是什么?