【发布时间】:2020-02-02 02:38:42
【问题描述】:
当函数被输入到模板中时尝试获取函数签名相当容易,只需执行以下操作:
template <class OutType, class... ArgTypes>
void foo(OutType (*func)(ArgTypes...));
获取非静态成员函数只是稍微复杂一点:
template <class OutType, class MemberOf, class... ArgTypes>
void foo(OutType (MemberOf::*func)(ArgTypes...));
// or
template <class OutType, class MemberOf, class... ArgTypes>
void foo(OutType (MemberOf::*func)(ArgTypes...) const);
但是,当输入法是否为 const 无关紧要时,如何将上面的两个函数声明合二为一呢?
【问题讨论】:
-
取决于你需要什么
template<typename Func> void foo(Func func)是我的第一个goto。 -
@NathanOliver 不幸的是,我需要函数中可用的签名中的所有类型。
-
我同意 Nathan 的观点,使用
std::invoke你可以支持的不仅仅是函数指针 -
@MatthewL 那么
template <class OutType, class... ArgTypes> void foo(std::function<OutType(ArgTypes...)>);呢? -
这似乎可行,但
foo(std::function<[whole function signature]>(&bar::do))感觉不必要地冗长,尤其是描述性函数/类名
标签: c++ c++11 templates methods constants