Are there uses of std::forward, where the argument is not a variable name?

75 Views Asked by At

In most cases the type of std::forward's argument is a forwarding reference:

template <class T>
void CallF(T&& value) {
    F(std::forward<T>(value));
}

In rarer cases the type is not a forwarding reference (FWD is taken from P0644):

#define FWD(x)  std::forward<decltype(x)>(x)

template <class T>
struct Wrapper {
    void operator()(T x1, T& x2, T&& x3) const {
        f(FWD(x1), FWD(x2), FWD(x3));
    }

    void (*f)(T, T&, T&&);
};

But, in both cases the argument itself is the name of a variable (value, x1, x2, x3). Are there cases where it is not a variable name, but some other expression?

2

There are 2 best solutions below

2
Christian Stieber On

Check out https://en.cppreference.com/w/cpp/utility/forward -- in particular, the "transforming wrapper".

I haven't used something like that (yet?) -- but a lot of the related stuff is still the black belt category for me.

1
Artyer On

In the past, I've created a pointer to an argument, then needed to forward *p as the value category of the original argument. Something like:

extern "C" void external_library(void callback(void*), void* data);

template<typename F>
void cpp_wrap(F&& f) {
    auto* pf = std::addressof(f);
    void(* callback)(void* data) = [](void* pf){
        std::forward<F>(*static_cast<std::add_pointer_t<F>>(pf))();
    };
    external_library(callback, pf);
}