Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template for calling functions

I have to call different functions in same manner:

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

I want to simplify source code, and use something like this:

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;
}

And make call look like:

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

Obviously, my template does not work, and I am not sure how to fix it:

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 *'

And finnaly, how I can fix(or rewrite) my template to make it work as I expecting?

like image 359
crashtua Avatar asked Jun 29 '26 12:06

crashtua


1 Answers

I'm guessing that the compiler interprets NULL as an int (see 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.

In the example below, see make_vix_2's call:

#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);                                                                                                          
}
like image 94
Ami Tavory Avatar answered Jul 01 '26 02:07

Ami Tavory