可变参数的冲突类型

Conflicting types for variadic parameter

本文关键字:冲突 类型 参数 变参      更新时间:2023-10-16

我正在尝试编写一个通用的调用函数。

它具有以下语法:

template<int Index, typename ReturnType, typename... Parameter>
ReturnType invokeGlobalFunction(Parameter... parameters)
{
return invocator->invoke<ReturnType>(Index, parameters...);
}

接下来,我尝试从中导出两个不同的功能点,如下所示:

registerFunction(::someGlobalFunction, &invokeGlobalFunction<0, void>);
registerFunction(::someOtherFunction, &invokeGlobalFunction<1, int>);

其中someGlobalFunction有原型void someGlobalFunction()someOtherFunction有原型int someOtherFunction(int, const char *)

在第一次调用时,它的工作方式类似于一个魅力,但是第二次调用会抛出错误:candidate template ignored: deduced conflicting types for parameter 'Parameter' (<int, const char *> vs. <>)

这意味着,编译器(顺便说一句,Ubuntu系统上的g ++ 7.4.0)不会像我期望的那样使用不同的参数集使invokeGlobalFunction过载。

注意:当我在调用中显式设置参数类型时

registerFunction(::someOtherFunction, &invokeGlobalFunction<1, int, int, const char *>);

编译器很高兴地接受它,但如果可能的话,我想避免这种情况。

作为奖励,如果我可以在每次索引更改时以某种方式创建一个唯一的函数,那就太好了,因为这将允许我拥有具有相同参数但不同返回类型的函数(据我所知这是非法的)。

谢谢。

但如果可能的话,我想避免这种情况。

据我所知,不是模板函数。

问题在于模板参数不是单个对象,而是一组对象,其中函数只能接受集合中的一个对象。

当你写的时候

&invokeGlobalFunction<1, int>

你选择一个精确的函数,Index = 1ReturnType = int和(这是重点)一个空的Parameter...列表。

建议:如果可以,使用模板方法在模板struct中转换invokeGlobalFunction()

作为

template <int Index, typename ReturnType>
struct invokeStruct
{
template <typename ... Parameters>
ReturnType operator() (Parameters ... parameters)
{
// ... 
}
};

这样你就有了一组结构,在每个结构中都有一组operator();将invokeStruct<1, int>{}作为参数传递,你传递一个对象,但在它里面,你有一组可用的方法。