【问题标题】:C++ Function Pointer issueC++ 函数指针问题
【发布时间】:2009-05-08 14:16:22
【问题描述】:

由于某种原因,试图将指向该函数的指针传递给可变参数函数会产生以下错误:

1>c:\... : error C2664: 'PyArg_ParseTuple' : cannot convert parameter 3 from 'int (__cdecl *)(PyObject *,void *)' to '...'
1>        Context does not allow for disambiguation of overloaded function

PyArg_ParseTuple(args, "O&O&:CreateWindow",
    &Arg_Size2U<1>, &size,
    &Arg_String<2>, &title);

我不确定问题出在哪里,因为模板函数没有过载,并且模板参数是明确定义的,所以没有问题要为哪个函数传递指针......

是否有某种方法可以避免为每个参数转换函数创建大量版本,但如果出现错误,仍然可以在异常中包含参数编号? (更好的方法是将参数编号作为参数传递,因此我的 dll 中没有该函数的多个副本。)

编辑: 这似乎也导致编译错误。有没有办法创建指向模板函数的函数指针,还是我需要与普通函数不同?

int (*sizeConv)(PyObject *,void *) = Arg_MakeSize2U<1>;
1>c:\... : error C2440: 'initializing' : cannot convert from 'int (__cdecl *)(PyObject *,void *)' to 'int (__cdecl *)(PyObject *,void *)'
1>        None of the functions with this name in scope match the target type

函数声明为:

template<int ARG> int Arg_MakeSize2U(PyObject *obj, void *out)

编辑2: 添加运营商的地址又给出了另一个不同的错误......

int (*sizeConv)(PyObject *,void *) = &Arg_MakeSize2U<1>;

1>c:\... : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'int (__cdecl *)(PyObject *,void *)'
1>        None of the functions with this name in scope match the target type

【问题讨论】:

  • Arg_Size2U的定义是什么?
  • 由于这似乎与 Python/Swig 相关,您应该提供更多上下文。
  • 实际上,虽然我使用 python C-APi 遇到了它,但进一步的测试表明它通常发生在 varaidc 函数参数和模板函数中。同样简单地尝试创建一个函数指针会产生一个错误,尽管一个不同的......

标签: c++ templates function-pointers variadic-functions function-templates


【解决方案1】:

这在 VC++ 2008 中编译得很好:

struct PyObject;

template<int ARG> int Arg_MakeSize2U(PyObject *obj, void *out)
{
    return 0;
}

int main()
{
    int (*sizeConv)(PyObject *,void *) = &Arg_MakeSize2U<1>;
    sizeConv(0, 0);
}

所以你必须做一些不同的事情。也许你确实有超载而你没有注意到。发布更多上下文将有助于更好地诊断问题。

【讨论】:

    【解决方案2】:

    从第二个错误听起来编译器找不到实现。您的模板函数定义在您声明模板的头文件中吗?

    【讨论】:

    • 是的,但是这个头文件包含在预编译头文件中,会不会在VS2008下导致问题?
    • 我将标题直接包含在我遇到问题的 cpp 中,完全一样的错误。
    • 我的意思是模板的主体必须在标题中。如果不是,那可以解释第二个错误。模板 void myFunc(T arg) { arg+1; }
    • 当我说是时,我的意思是,模板函数的整个实现都在标题中。
    猜你喜欢
    • 2016-05-31
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多