我正在尝试(也许是愚蠢的)使用模板函数为Python扩展创建成员函数:
template < typename T >
static PyObject* getName( T* self, PyObject* args )
{
std::string name = self->obj->getName();
return PyString_FromString( name.c_str() );
}
struct PyMyObject
{
PyObject_HEAD
MyObject* obj;
};
static PyMethodDef PyMyObject_methods[] = {
{"getName", (PyCFunction) getName< PyMyObject >, METH_VARARGS,
"return this object's name" },
{NULL}
};
唉,当我这样做并试图编译我收到了:
g++ test.cpp -I /usr/include/python2.4 -lpython2.4
test.cpp:34: error: insufficient contextual information to determine type
但是,如果我明确地指定一个函数指针然后将函数指针传递给方法定义,那么它将编译而不会出现错误:
PyObject* (*PyMyObject_getName)( PyMyObject*, PyObject* ) = getName< PyMyObject >;
static PyMethodDef PyMyObject_methods[] = {
{"getName", (PyCFunction) PyMyObject_getName, METH_VARARGS,
"return this object's name" },
{NULL}
};
为什么需要显式声明函数指针?在我看来,getName< PyMyObject >
包含了编译器生成函数所需的所有类型信息,那么为什么编译器需要额外的&#34;上下文信息&#34;?