Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
Sergei Krivonos Avatar asked Nov 04 '16 19:11

Sergei Krivonos


1 Answers

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

like image 146
krzaq Avatar answered Nov 11 '22 03:11

krzaq