PrevUpHomeNext

Home:: tiv.cc

Template Rvalue Reference


cpp: c++

Rvalue reference

Rvalue reference accepts Rvalue, but does not accept Lvalue.

#include <utxcpp/core.hpp>

void fn(utx::i32 &&) {}

int main()
{
// fn accepts Rvalue, but does not accept Lvalue.
	fn(123); // OK
	utx::i32 x;
	// fn(x); // ERROR
}

Template Rvalue Reference

Template Rvalue reference accepts both Lvalue and Rvalue.

This page is outdated, please refer forwarding references at cppreference:

https://en.cppreference.com/w/cpp/language/reference

#include <utxcpp/core.hpp>

template <typename T>
void fn(T &&) {}

int main()
{
// OK: fn accepts both Lvalue and Rvalue.
	fn(123);
	utx::i32 x;
	fn(x);
}

Template Rvalue Reference: decay

After using std::decay_t or std::remove_reference_t, template Rvalue reference does not accept Lvalue again.

#include <utxcpp/core.hpp>

template <typename T>
void fn(std::remove_reference_t<T> &&) {}

int main()
{
// fn accepts Rvalue, but does not accept Lvalue again.
	fn<utx::i32>(123); // OK
	utx::i32 x;
	// fn<utx::i32>(x); // ERROR
}

More Issues

Sometimes std::remove_reference_t is not enough to satisfy demand, for example you want to accept Lvalue or Rvalue, but not both, when the template inferences to a "const".

In such case, you will need more:

std::remove_cvref_t
std::remove_const_t
std::remove_reference_t
std::remove_cv_t
std::decay_t

Last revised: March 27, 2023 at 03:21:19 GMT


PrevUpHomeNext