Question

I have a construct in a form:

template<class T>
    void do_something_with_it(T*&& ptr)
    {
//here I can do something with this ptr
    }

    template<class T,class... Args>
    void do_something_with_them(T*&& ptr, Args&&... args)
    {
        do_something_with_it(std::forward<T&&>(ptr));
        do_something_with_them(std::forward<Args&&>(args)...);
    }

but for some reason I cannot forward those arguments. Is there a way to do it?
I'm using gcc 4.6.1.

Was it helpful?

Solution

Chances are that you get compile time errors, because T*&& is not a perfect forwarding vehicle. Only T&& is. So your ptr parameter only accepts rvalues. And in addition to that, your std::forward<T&&> should be std::forward<T*>, but of course now that you have the other error anyway this is irrelevant. And in addition to that the call to do_something_with_them misses to hit a base case of do_something_with_them with zero parameters, because if args is empty...

If you really only want to accepts pointers, you can work with enable_if and is_same or is_convertible. But then of course I don't think it's "forwarding" anymore. What about

template<typename T, typename ...Args>
auto do_something_with_them(T&&t, Args&&...args)
  -> decltype(do_something_with_it(std::forward<T>(t)))
{ ... }

That way you let do_something_with_it decide whether or not it accepts the argument (if you want you can put the recursive call into that decltype too. I leave it as an exercise to the reader as to what operator might be needed here). But of course do_something_with_it has the same problem too about not being generic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top