可变参数的冲突类型

Conflicting types for variadic parameter

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

语法如下:

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 *>);

编译器很乐意接受它,但我想尽可能避免这种情况。

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

谢谢。

but I'd like to avoid that, if possible.

据我所知,模板函数没有。

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

写的时候

&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>{} 作为参数,你传递一个对象,但在它里面,你有一组可用的方法。