Sergei Sergei - 1 month ago 5
C++ Question

How to detect std::reference_wrapper in C++ at compile time

Lets say we have some variadic template and need to treat

std::reference_wrapper
parameters differently.
How can we achieve that?

Answer

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)...
    };
}

demo