简体   繁体   English

将std :: endl转换为函数指针

[英]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: @Kerrek SB提出了以下解决方案:

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 . 这使我想做什么很明确,而不是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). (我无法弄清楚如何使它透明地用于方法,而且我认为从理论上讲不可能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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