diff options
author | johannst <johannst@users.noreply.github.com> | 2023-05-29 20:34:16 +0000 |
---|---|---|
committer | johannst <johannst@users.noreply.github.com> | 2023-05-29 20:34:16 +0000 |
commit | eaad036407c9546be0de27f61745fef4b6856e56 (patch) | |
tree | c270e3fbc87f3b7c9fc25ac60f4f8f611962de5e /development/c++/fwd.cc | |
parent | 87c538b89ea68cf0c133a9243097ffac646e6739 (diff) | |
download | notes-eaad036407c9546be0de27f61745fef4b6856e56.tar.gz notes-eaad036407c9546be0de27f61745fef4b6856e56.zip |
deploy: d2013ee5952bbcf88906a832748783e372f3a939
Diffstat (limited to 'development/c++/fwd.cc')
-rw-r--r-- | development/c++/fwd.cc | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/development/c++/fwd.cc b/development/c++/fwd.cc new file mode 100644 index 0000000..802d5bb --- /dev/null +++ b/development/c++/fwd.cc @@ -0,0 +1,58 @@ +// Copyright (C) 2023 johannst + +#include <cstdio> +#include <utility> + +struct M {}; + +// -- CONSUMER ----------------------------------------------------------------- + +void use(M&) { + puts(__PRETTY_FUNCTION__); +} + +void use(M&&) { + puts(__PRETTY_FUNCTION__); +} + +// -- TESTER ------------------------------------------------------------------- + +template<typename T> +void wrapper(T&& param) { // forwarding reference + puts(__PRETTY_FUNCTION__); + // PARAM is an lvalue, therefore this always calls use(M&). + use(param); +} + +template<typename T> +void fwd_wrapper(T&& param) { // forwarding reference + puts(__PRETTY_FUNCTION__); + // PARAM is an lvalue, but std::forward returns PARAM with the same value + // category as the forwarding reference takes. + use(std::forward<T>(param)); +} + +// -- MAIN --------------------------------------------------------------------- + +int main() { + { + std::puts("==> wrapper rvalue reference"); + wrapper(M{}); + // calls use(M&). + + std::puts("==> wrapper lvalue reference"); + struct M m; + wrapper(m); + // calls use(M&). + } + { + std::puts("==> fwd_wrapper rvalue reference"); + fwd_wrapper(M{}); + // calls use(M&&). + + std::puts("==> fwd_wrapper lvalue reference"); + struct M m; + fwd_wrapper(m); + // calls use(M&). + } +} |