How to have a templated function require its argument be passed by rvalue reference?

61 views Asked by At

Because of the confusing syntax of forwarding references and rvalue references, it's not clear to me how I would write a function that takes some type, T, by rvalue reference. That is, while

template <typename T> void foo(T x);

takes x by value and

template <typename T> void foo(T& x);

by reference, and

template <typename T> void foo(T* x);

by pointer, when we say

template <typename T> void foo(T&& x);

suddenly it's taking x by forwarding reference not by rvalue reference. What's the Right Way to say foo takes x by forwarding reference? Like this?

template <typename T>
void foo(T&& x) {
    static_assert(std::is_rvalue_reference_v<T&&>, "x must be an rvalue reference.");
1

There are 1 answers

4
bipll On BEST ANSWER
template<class T>
void f(T &&)
requires(!std::is_lvalue_reference_v<T>);