简体   繁体   中英

Cast std::endl to a function pointer

This is a follow-up question to How template function chooses parameter?

@Kerrek SB proposed the following solution:

Func(static_cast<std::ostream&(&)(std::ostream&)>(std::endl));

I also found that the following code works for me too:

Func(static_cast<std::ostream&(*)(std::ostream&)>(std::endl));

Question > Which one is the preferred method?

I would do this:

template<class Sig>
struct reference_to_function {};
template<class R, class... Args>
struct reference_to_function<R(Args...)> {
  using type = R(&)(Args...);
};
template<class Sig>
using sig_t = typename reference_to_function<Sig>::type;

template<class Sig>
sig_t<Sig> pick_signature( sig_t<Sig> f ) { return f; }

then:

Func( pick_signature<std::ostream&(std::ostream&)>( std::endl ) );

which makes it explicit what I want to do, rather than a static_cast .

Maybe make a second version that takes a class type and a signature, and does it for methods as well. (I cannot figure out how to make it work transparently for methods, and I think theoretically it cannot).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM