【发布时间】:2014-10-06 13:42:13
【问题描述】:
我正在尝试找出一种更简洁的方式来编写这段相当丑陋的代码:
class PythonExtensionBase : public PyObject
{
:
public:
// helper functions to call function fn_name with 0 to 9 args
Object callOnSelf( const std::string &fn_name );
Object callOnSelf( const std::string &fn_name, const Object &arg1 );
Object callOnSelf( const std::string &fn_name, const Object &arg1, const Object &arg2 );
Object callOnSelf( const std::string &fn_name, const Object &arg1, const Object &arg2, const Object &arg3 );
:
(一直到 9)
这些功能在对应的.cxx中实现:
Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name )
{
Py::TupleN args;
return self().callMemberFunction( fn_name, args );
}
Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name,
const Py::Object &arg1 )
{
Py::TupleN args( arg1 );
return self().callMemberFunction( fn_name, args );
}
Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name,
const Py::Object &arg1, const Py::Object &arg2 )
{
Py::TupleN args( arg1, arg2 );
return self().callMemberFunction( fn_name, args );
}
Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name,
const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3 )
{
Py::TupleN args( arg1, arg2, arg3 );
return self().callMemberFunction( fn_name, args );
}
:
有效的任务是概括:
X( A a, B b1, B b2, B b3 ) {
foo( b1, b2, b3 );
}
我可以看到可变参数模板可能是要走的路,但我很难理解如何使用它。
TupleN 类定义如下:
class TupleN: public Tuple
{
public:
TupleN()
: Tuple( 0 )
{
}
TupleN( const Object &obj1 )
: Tuple( 1 )
{
setItem( 0, obj1 );
}
TupleN( const Object &obj1, const Object &obj2 )
: Tuple( 2 )
{
setItem( 0, obj1 );
setItem( 1, obj2 );
}
TupleN( const Object &obj1, const Object &obj2, const Object &obj3 )
: Tuple( 3 )
{
setItem( 0, obj1 );
setItem( 1, obj2 );
setItem( 2, obj3 );
}
:
virtual ~TupleN()
{ }
};
【问题讨论】:
-
我真诚地希望唯一的原因是因为作者最初没有可用的 C++11 功能。如果情况确实如此,并且上述问题已经得到解决,那么确实可以将其中的大部分内容都废弃为可变参数解决方案。
-
替代可变参数的解决方案,您可以使用
std::initializer_list<Object>。
标签: c++ variadic-templates variadic