【问题标题】:Generating a sequence of type T at compile time在编译时生成类型 T 的序列
【发布时间】:2016-10-26 17:30:56
【问题描述】:

我有以下问题:

template< typename callable, typename T , size_t... N_i>
void foo()
{
  using callable_out_type =  std::result_of_t< callable( /* T , ... , T <- sizeof...(N_i) many */ ) >;

  // ...
}

我想得到callable 的结果类型,它将sizeof...(N_i) 类型为T 的许多参数作为其输入,例如callable(1,2,3)T==intsizeof...(N_i)==3 的情况下。如何实现?

非常感谢。

【问题讨论】:

标签: c++ c++14 callable


【解决方案1】:

我们可以使用类型别名来挂钩N_i 的扩展,但总是返回T

template <class T, std::size_t>
using eat_int = T;

template< typename callable, typename T , size_t... N_i>
void foo()
{
  using callable_out_type = std::result_of_t< callable(eat_int<T, N_i>...) >;

  // ...
}

【讨论】:

    【解决方案2】:

    为什么不简单地使用:

    using callable_out_type = std::result_of_t< callable( decltype(N_i, std::declval<T>())...) >;
    

    你也可以使用从Columbo's answer借来的技巧:

    using callable_out_type =  std::result_of_t< callable(std::tuple_element_t<(N_i, 0), std::tuple<T>>...) >;
    

    甚至:

    using callable_out_type =  std::result_of_t< callable(std::enable_if_t<(N_i, true), T>...) >;
    

    【讨论】:

      【解决方案3】:

      您可以编写以下帮助程序

      template<typename T, size_t>
      using type_t = T;
      
      template<typename Callable, typename T, size_t... Is>
      auto get_result_of(std::index_sequence<Is...>) -> std::result_of_t<Callable(type_t<T,Is>...)>;
      
      template<typename Callable, typename T, size_t N>
      using result_of_n_elements = decltype(get_result_of<Callable, T>(std::make_index_sequence<N>{}));
      

      然后在你的foo 你会写

      template< typename callable, typename T , size_t N>
      void foo()
      {
          using callable_out_type = result_of_n_elements<callable, T, N>;
      }
      

      live demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-06
        • 1970-01-01
        • 2013-05-12
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        相关资源
        最近更新 更多