C++ 如何在函数指针中设置参数模板?

C++ 如何在函数指针中设置参数模板?,c++,c++11,templates,function-pointers,function-templates,C++,C++11,Templates,Function Pointers,Function Templates,我有一个模板: template<typename T> void testFuction(int(*testFunc)(CallBack, void *, T *)) { // define CallBack callback, void* param1, T* param2 // ... testFunc(callback, param1, param2); } 模板 void testFuction(int(*testFunc)(回调,void*,T*

我有一个模板:

template<typename T>
void testFuction(int(*testFunc)(CallBack, void *, T *))
{
    // define CallBack callback, void* param1, T* param2
    // ...
    testFunc(callback, param1, param2);
}
模板
void testFuction(int(*testFunc)(回调,void*,T*))
{
//定义回调,void*param1,T*param2
// ...
testFunc(回调,param1,param2);
}
它起作用了,但看起来很糟糕, 我想做一些类似的事情:

template<typename T>
// using TestFunc<T> = std::function<int(CallBack, void *, T *)>
void testFuction(TestFunc<T> testFunc)
{
   // define CallBack callback, void* param1, T* param2
   // ...
   testFunc(callback, param1, param2);
}
模板
//使用TestFunc=std::function
无效TestFunction(TestFunc TestFunc)
{
//定义回调,void*param1,T*param2
// ...
testFunc(回调,param1,param2);
}
但它不起作用

有人能帮我吗? 我还用一些额外的参数重载了许多类似的函数,它们看起来很难看。
我想定义一次
TestFunc
,然后在模板函数中再次使用它。

您可以为模板函数指针提供一个类型别名,如下所示

#include <utility> // std::forward

template<typename T>
using FunPointerT = int(*)(CallBack, void*, T*);

template<typename T, typename... Args>
void testFuction(FunPointerT<T> funcPtr, Args&& ...args)
{
   // variadic args, in the case of passing args to testFuction
   funcPtr(std::forward<Arg>(args)...);
}
#包括//标准::转发
样板
使用FunPointerT=int(*)(回调,void*,T*);
样板
void testFuction(FunPointerT funcPtr,Args&…Args)
{
//可变参数,在将参数传递给TestFunction的情况下
funcPtr(std::forward(args)…);
}
根据Op的要求进行更新

template<typename T> 
void testFuction(FunPointerT<T> funcPtr) 
{
   // ...
   funcPtr(/* args from local function scope */);
}
模板
无效测试功能(FunPointerT funcPtr)
{
// ...
funcPtr(/*来自本地函数作用域的参数*/);
}

让我们看一个简化的示例:

#包括
样板
无效测试功能(标准::功能f){
f(nullptr);
}
无效使用(int*i);
int main(){
测试功能(使用int ptr);
}
编译失败:
T
不能推断为
int
。它与
void(*f)(T*)
一起工作的原因是,如果传递函数指针,则可以推断
T
,但函数指针不是
std::function

您有一些可能的解决方案。您可以手动指定
T

测试功能(使用int ptr);
您可以传递一个
std::function
,这样就可以推断出
T

test_函数(std::function{use_int_ptr});
//或者在C++17中使用CTAD
test_函数(std::function{use_int_ptr});
制作一个转发函数,将函数指针封装在如上所述的
std::function
s中,需要手动传递其他可调用函数的
std::function
s:

模板
无效测试函数(无效f(T*)){
test_函数(std::function{f});
}
或者只需在原始函数中使用任意类型:

模板
无效测试功能(F&&F){
f(nullptr);
}

到底什么不起作用?也许您首先需要一个别名模板,
使用TestFunc=std::function的模板?编译器说
没有匹配函数用于调用'VendorTester::testFuction(int(&)(CallBack,void*,SomeData*)
不,我不打算使用forward参数,我的编译器说
没有匹配函数用于调用'VendorTester::testFuction(int(&)(CallBack,void*,SomeData*)
VendorTester.testFunction(SomeFunctionToBeTest);
即使它们有相同的参数,我也必须使用别名而不使用std::function,谢谢你,杰乔