我一直潜伏在这里,试图弄清楚Functor是否可以做我需要它做的事情。
我想要做的是包装对类方法的调用,并以某种方式捕获函数返回的值。鉴于我的Functor类,我需要做什么才能将我的注释转换为代码:
template < typename Func >
class MySpecializedFunctor
{
Func t;
MyObject& p;
public:
MyFunctor( MyObject &obj, Func f )
{
p = obj;
t = f;
}
void runFunc( ... )
{
// Can I use an ellipsis '...' to pass values into t->xxxx() ???
// Assume the first param is always time, the others are never the same
bool b = p->t( time( NULL ), /* first value of ... */, /* second value of ... */ );
if ( !b )
{
// log error here
}
}
}
因为这是一个类型的Functor,被包装的函数可以有n个参数。
这可能吗?
编辑:我不能使用C ++ 0X。
答案 0 :(得分:3)
使用可变参数模板:
template <typename... Args>
void runFunc(Args&&... args)
{
bool b = p->t(time(NULL), std::forward<Args>(args)...);
if ( !b )
{
// log error here
}
}
或者重载 runFunc ,如果您的编译器不支持可变参数模板或完美转发:
// this one support 3 const arguments, you will need to overload
// all variations of arguments count and constness
template <typename Arg1, typename Arg2, typename Arg3>
void runFunc(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3)
{
bool b = p->t(time(NULL), arg1, arg2, arg3);
if ( !b )
{
// log error here
}
}