Ben
Ben

Reputation: 9703

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

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.");

Upvotes: 1

Views: 89

Answers (1)

bipll
bipll

Reputation: 11940

template<class T>
void f(T &&)
requires(!std::is_lvalue_reference_v<T>);

Upvotes: 1

Related Questions