用于调用函数的 C++ 模板

C++ template for calling functions

我必须以相同的方式调用不同的函数:

VixHandle jobHandle = VIX_INVALID_HANDLE;
jobHandle = VixHost_Connect(VIX_API_VERSION, provider, host.c_str(), 0, user.c_str(), password.c_str(), 0, VIX_INVALID_HANDLE,NULL, NULL);
VixHandle result = Vix_waitJobResult(jobHandle);

我想简化源代码,使用类似这样的东西:

template <typename FUNC, typename ... ARGS>
VixHandle VIX_CALL(FUNC fun, ARGS ... arg){
    VixHandle result = VIX_INVALID_HANDLE;
    VixHandle jobHandle = VIX_INVALID_HANDLE;
    jobHandle = fun(arg...);
    result = Vix_waitJobResult(jobHandle);
    Vix_ReleaseHandle(jobHandle);
    return result;
}

并使通话看起来像:

VixHandle hostHandle = VIX_CALL(VixHost_Connect, VIX_API_VERSION, provider, host.c_str(), 0, user.c_str(), password.c_str(), 0, VIX_INVALID_HANDLE,NULL, NULL);

显然,我的模板不起作用,我不确定如何修复它:

C:\Users\crashtua\Documents\CppVix\vix_api_helper.h:12: error: C2664: 'VixHandle (int,VixServiceProvider,const char *,int,const char *,const char *,VixHostOptions,VixHandle,VixEventProc (__cdecl *),void *)': cannot convert argument 10 from 'int' to 'void *'

最后,我如何修复(或重写)我的模板以使其按预期工作?

我猜测编译器将 NULL 解释为 int(参见 this question or, better, Scott Meyer's Effective Modern C++). You know that the intent is a pointer, but the compiler doesn't. You should use nullptr

在下面的示例中,请参阅 make_vix_2 的调用:

#include <utility>
class vix_handle{};
template<class Fn, typename ...Args>
void vix_call(Fn fn, Args &&...args)
{
    vix_handle job_handle = fn(std::forward<Args>(args)...);
}

vix_handle make_vix_0(int, int, int){return vix_handle();}
vix_handle make_vix_1(float){return vix_handle();}
vix_handle make_vix_2(char *){return vix_handle();}

int main()
{
    vix_call(make_vix_0, 1, 2, 3);
    vix_call(make_vix_1, 1.0);
    vix_call(make_vix_2, nullptr);                                                                                                          
}