Add utilities for working with `std::reference_wrapper`
This adds three utilities (stolen from staging/dune-functions!315 (merged)) and a
corresponding test for working with std::reference_wrapper
:
-
IsReferenceWrapper_v<T>
allows to check ifT
is an instantiation ofstd::reference_wrapper
- The function
resolveRef(t)
either returnst.get()
ort
depending on whethert
is astd::reference_wrapper
or a plain l-value reference. -
ResolveRef_t<T>
provides the resolved type forT
.
These utilities allow to support storing data members of classes by value or
reference transparently suing the following pattern. The class always stores
values, but supports passing std::ref(...)
to opt-in store-by-reference.
Handling the latter can be done without boilerplate code using the
provided utilities:
template<class StoredT>
struct SomeWrapper {
using T = ResolveRef_t<StoredT>;
SomeWrapper(const StoredT& t) : t_(t) {}
void callFoo() const {
resolveRef(t_).foo();
}
StoredT t_;
};
[...]
// Store t by value
auto w1 = SomeWrapper(t);
w1.callFoo();
// Store t by reference
auto w2 = SomeWrapper(std::cref(t));
w2.callFoo();
Merge request reports
Activity
mentioned in merge request !1101 (closed)
I'm really supporting this. I'm using this reference wrapper utility quiet a lot recently. It makes storing reference more explicit.
What do you think could be a "best-practice" when passing the stored object to the wrapper class? You have passed to the constructor by
const&
. An alternative could be:SomeWrapper(StoredT t) : t_(std::move(t)) {}
My motivation for writing it like this is: It tells the user that the passed object is stored by value right away in the constructor.
That's a good argument. But as far as I know this case is neither listed for guaranteed nor for optional copy-elision. Hence we have to hope for compiler optimization which may not work in the case of side effects. Thus I personally tend to pass references. But maybe I'm to worried here.
- Resolved by Carsten Gräser
- Resolved by Carsten Gräser
- Resolved by Carsten Gräser
added 1 commit
- da4bd702 - Add utilities for working with `std::reference_wrapper`
mentioned in merge request dune-grid!577 (merged)
- Resolved by Simon Praetorius
Any objections to merging this?
mentioned in commit fc637911
requested review from @simon.praetorius