Lo1234
Lo1234

Reputation: 45

Proper way of using Variadic template function call with string arguments c++

Hello what wrong Iam doing here in using variadic templates via string? How to use it properly to achieve the below task?

#include <iostream>
#include<string>

int sum(int a, int b, int c, int d) { return a+b+c+d; }
int strcopy(char* str)   { strcpy(str,"Hello World!!!"); return 1; }

template<typename Func, typename... Args>
auto MainCall(Func func, Args&&... args)-> typename std::result_of<Func(Args...)>::type
{
    return func(std::forward<Args>(args)...);
}

template<typename... funcname, typename... Args>
int CallFunction(std::string const& Func , Args&&... args)
{

    if(!Func.compare("sum"))
    {
        return MainCall(sum, args...);
    }
    else if(!Func.compare("strcopy"))
    {
        return MainCall(strcopy, args...);
    }
    else
    {
        return 0;
    }

}


int _tmain(int argc, _TCHAR* argv[])
{
    char buffer[512];
    cout <<  CallFunction("sum",1,2,3,4) << end1; /* How to properly execute "sum" function by sending string name to variadic function template function??? */
    CallFunction("strcopy",buffer); /* How to properly execute "strcopy" function by sending string name to variadic function template function??? */
    printf("Buffer says = %s" , buffer); /* Should print "Hello World!!!" */
    getchar();
    return 0;
}

I get compiler error like
error C2197: 'int (__cdecl *)(char *)' : too many arguments for Maincall
see reference to class template instantiation 'std::_Result_type<false,_Fty,_V0_t,_V0_t,_V2_t,_V2_t,_V4_t,_V4_t,_V6_t,_V6_t,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil>' being compiled

Upvotes: 0

Views: 402

Answers (1)

bolov
bolov

Reputation: 75924

The problem is:

When you call:

CallFunction("sum", 1, 2, 3, 4)

The templated function CallFunction is instantiated with funcanme={} (totally useless, you can remove it) and Args={int, int, int, int}. In this function you have a line: MainCall(strcopy, args...); which in this case becomes: MainCall(strcopy, 1, 2, 3, 4) which in turn calls strcopy(1, 2, 3, 4) which is invalid call.

There is no (non-convoluted) way in C++ to call function with different prototypes based on a name known at runtime and taking a variadic argument pack.

Upvotes: 3

Related Questions