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

Cast std::endl to a function pointer

本文关键字:函数 转换 指针 std endl      更新时间:2023-10-16

这是模板函数如何选择参数的后续问题?

@Kerrek SB提出了以下解决方案:

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

我还发现以下代码也适用于我:

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

问题>首选哪种方法?

我会这样做:

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; }

然后:

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

这使它明确了我想做什么,而不是static_cast

也许可以制作第二个版本,它采用类类型和签名,并对方法进行签名。(我不知道如何让它在方法中透明地工作,我认为理论上也不可能)。