Skip to content

Instantly share code, notes, and snippets.

@merryhime
Created January 20, 2017 00:47
Show Gist options
  • Save merryhime/d9d4221dd438fbe601e016802fced57e to your computer and use it in GitHub Desktop.
Save merryhime/d9d4221dd438fbe601e016802fced57e to your computer and use it in GitHub Desktop.
Was writing a tuple class for fun.
template <typename... Ts>
class tuple {
template <typename T>
T& get();
template <typename T>
T const& get() const;
};
One issue here is the following line(s) of code:
tuple<A, B> get_tuple();
A a = get_tuple().get<A>();
would result in an unnecessary copy of A, because even though `get_tuple` returns an rvalue, `get<A>` returns a const ref.
This is not only inefficient, but would break if A was non-copyable.
One way to fix this with a rvalue ref qualified version of get:
template <typename... Ts>
class tuple {
template <typename T>
T& get() &;
template <typename T>
T&& get() &&;
template <typename T>
T const& get() const &;
};
Tada.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment