Search code examples
c++template-argument-deduction

Type deduction of reference_wrappers with Args


I have a template function:

template<class... Args>
void foo(Args&&... args)
{
    boo<std::decay_t<Args>...>(std::forward<Args>(args)...);
}

Now what I want to do is to call foo function several times like this:

int value = 123;
const int& cr_value = value;
foo(value );
foo(std::cref(value ));

In first case I call boo<int> in second case boo<std::const_reference_wrapper<int>> is called. Is there way to "dereference" reference_wrapper automaticaly without explicit using of get function for every argument in pack? The reason for this is that I want to call boo<const int&> in second case, not boo<std::const_reference_wrapper<int>>


Solution

  • You might do something like:

    template <typename T> struct unwrap {
        using type = T;
    };
    template <typename T> struct unwrap<std::reference_wrapper<T>> {
        using type = T&;
    };
    
    template <typename T> using unwrap_t = typename unwrap<T>::type;
    
    template<class... Args>
    void foo(Args&&... args)
    {
        boo<unwrap_t<std::decay_t<Args>>...>(std::forward<Args>(args)...);
    }
    

    Demo.