C++: reference wrappers and printf -


i have std::vector of std::reference_wrapper objects want print printf (without cout); now, if write

int a=5; std::reference_wrapper<int> b=a; printf("%i\n\n",b); 

i nosense number (i think address of a); obtain value have do

printf("%i\n\n",b.get()); 

is there way have automatic call .get() function in printf (e.g. different % specificator print me reference_wrapper content) can make generalized function works both std::reference_wrapper<type> , type?

you want @ least consider using c++ io library instead of legacy c functions. being said, can write wrapper around printf provide unwrapping of reference wrappers:

template<typename... params> void my_printf(char const* fmt, params&&... ps) {     printf(fmt, unwrap(std::forward<params>(ps))...); } 

with unwrap implemented follows:

template<typename t> decltype(auto) unwrap_impl(t&& t, std::false_type){     return std::forward<t>(t); }  template<typename t> decltype(auto) unwrap_impl(t&& t, std::true_type){     return t.get(); }  template<typename t> decltype(auto) unwrap(t&& t) {     return unwrap_impl(std::forward<t>(t), is_reference_wrapper<std::decay_t<t>>{}); } 

and is_reference_wrapper trait:

template<typename t> struct is_reference_wrapper : std::false_type {};  template<typename t> struct is_reference_wrapper<std::reference_wrapper<t>> : std::true_type{}; 

demo


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -