문제

I'm new to variadic templates in C++, so this question may seem kind of noobish to the experienced guys over here.

What im trying to do is create a proxy function that will be able to redirect my arguments to any other function using variadic templates.

My code is as follows:

template <typename Ret, typename ... Types>
Ret proxy_function(Types ... args)
{
    return MessageBoxA(args...);
}

int main(int argc, char* argv[])
{
    boost::any retval = proxy_function<boost::any>(NULL, "123", "456", 0);
}

On compilation, the compiler outputs the following error:

1>Main.cpp(107): error C2664: 'int MessageBoxA(HWND,LPCSTR,LPCSTR,UINT)' : cannot convert argument 1 from 'int' to 'HWND'

However, when I supply the following code it works just fine:

template <typename Ret, typename ... Types>
Ret proxy_function(Types ... args)
{
    return MessageBoxA(NULL, args...);
}

int main(int argc, char* argv[])
{
    boost::any retval = proxy_function<boost::any>("123", "456", 0);
}

Is there any reason in the world why the compiler won't be able to cast it to HWND type?

And another question I have in mind right now related to this issue - Is it possible to figure out the type of arguments inside a function? I would like to be able to do this stuff:

template <typename Ret, typename ... Types>
Ret proxy_function(Types ... args)
{
    psuedo-code:
        for arg in args:
            do_stuff<type(arg)>(arg);
}

Thanks in advance, Aviv

도움이 되었습니까?

해결책

Integral literal of value 0 implicitly converts to pointer. But in the call it ends up as a run-time function parameter, which is not a compile time constant, and therefore does not convert to nullpointer (even if it's 0). Use C++11 nullptr.


By the way, look up "perfect forwarding".

다른 팁

NULL is defined as 0 and the literal 0 is implicitly convertible to a pointer. This causes problems like the one you just mentioned so now there's a new type nullptr_t with object nullptr that is implicitly convertible to any pointer type and gives null (lowercase to represent the concept of null instead of thinking it gave NULL).

As for your second question in your particular usage you can use recursion like so:

    template <class T>
    void do_stuff(T && t){/* stuff here with t*/}

    template <class T, class ... Ts>
    void do_stuff(T && t, Ts && ... ts)
    {
        /* do stuff with t*/
        do_stuff(std::forward<Ts>(ts)...);
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top