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