在编译时生成 T 类型的序列

Generating a sequence of type T at compile time

我遇到以下问题:

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。如何实施?

非常感谢。

我们可以使用类型别名来挂钩 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>...) >;

  // ...
}

你可以编写以下助手

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

为什么不简单地使用:

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

你也可以使用从 :

借来的技巧
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>...) >;