【问题标题】:How to get std::bind function signature?如何获得 std::bind 函数签名?
【发布时间】:2021-04-19 17:00:52
【问题描述】:

我正在尝试为每个类似函数的类型(例如函数、lambdas、比较器)获取一个返回类型和一些参数。

/**
 * @brief Get some info about any function-like object at compile-time.
 * 
 * @tparam F function template.
 */
template<typename F, typename = void> 
struct function_traits;

// Catch functions
template<typename R, typename ...Args>
struct function_traits<R (Args...)>
{ 
    using return_type = R;

    static constexpr std::size_t argc = sizeof...(Args);

    template<size_t i> 
    struct get_arg
    {
        using type = std::tuple_element_t<i, std::tuple<Args...>>;
    };

    template<size_t i>
    using get_arg_t = typename get_arg<i>::type;
};

// Catch function pointers
template<typename R, typename ...Args>
struct function_traits<R (*)(Args...)> : function_traits<R (Args...)> {};

// Catch member functions
template<typename R, typename C, typename ...Args>
struct function_traits<R (C::*)(Args...)> : function_traits<R (Args...)> {};

// Catch member const functions
template<typename R, typename C, typename ...Args>
struct function_traits<R (C::*)(Args...) const> : function_traits<R (C::*)(Args...)> {};

// Catch lambda and structs with one operator()
template<typename F> 
struct function_traits<F, void> : function_traits<decltype(&F::operator())> {};

这适用于除std::bind 之外的所有内容,因为它具有多个operator() 函数。如何改进我的代码以从绑定中获取信息?

【问题讨论】:

  • 我会像使用here 一样利用std::function,让它为您解决问题。然后可以从std::functionoject的模板参数中提取信息
  • std::bind的结果类型有无限多个operator(),最多有无限多个参数。你要哪一个?
  • 它并没有真正回答你的问题,但我认为最好的解决方案是不使用std::bind。 Lambda 永远是更好的选择。
  • 旁白:Cs 不应该是争论的一部分,还是应该在某处提及?
  • @Caleth,为什么?仅用于自动扣款。

标签: c++ templates metaprogramming signature stdbind


【解决方案1】:

这适用于除std::bind之外的所有内容

您发现了没有唯一答案的(许多)案例之一。

对于重载函数,transparent comparatorsvisitors 和其他可以多种方式调用的类型也会失败。

我认为这就是为什么没有std::function_traits,而我们有std::is_invocable et.al。

【讨论】:

    猜你喜欢
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2012-10-15
    • 2016-04-26
    相关资源
    最近更新 更多