Lets say we have some variadic template and need to treat std::reference_wrapper
parameters differently.
How can we achieve that?
Asked
Active
Viewed 753 times
6

Sergei Krivonos
- 4,217
- 3
- 39
- 54
-
1Why do you need to do this? – OMGtechy Nov 04 '16 at 19:50
-
2In what way do you want to treat them differently? Print `os << "chicken"` when you print them, while using `os << t` on other types? Treat `reference_wrapper
&&` as `T&` while calling `.get()` on them? – Yakk - Adam Nevraumont Nov 04 '16 at 19:53
1 Answers
13
You can make a trait to tell if a type is reference_wrapper
template<typename T>
struct is_reference_wrapper : false_type {};
template<typename T>
struct is_reference_wrapper<reference_wrapper<T>> : true_type{};
Then you can use it to disambiguate:
template<typename T>
void do_stuff(T&& t, false_type)
{
cout << "Normal: " << t << endl;
}
template<typename T>
void do_stuff(T&& ref, true_type)
{
cout << "Ref: " << ref.get() << endl;
}
template<typename... Ts>
void foo(Ts&&... ts)
{
[[maybe_unused]] int arr[] = {
(do_stuff(forward<Ts>(ts), is_reference_wrapper<decay_t<Ts>>{}), 0)...
};
}

krzaq
- 16,240
- 4
- 46
- 61