1

我有一个函数模板,它接受一个任意嵌套的列表并返回一个数组:

#include <array>
#include <initializer_list>

template<size_t N, typename List>
std::array<size_t,N> some_function (const List& list)
{
    // N is the number of times the list is nested.
    std::array<size_t,N> arr;
    return arr;
}

当我将此函数用于某些嵌套std::initializer_list时,如下所示:

int main () {
    using List = std::initializer_list<std::initializer_list<double>>;
    List list = {{1.,2.,3.},{4.,5.,6.}};

    std::array<size_t,2> arr;
    arr = some_function (list);
    return 0;
}

我收到无法推断类型 N 的错误

无法推导出模板参数'N'</p>

问题

  • 如何改进我的函数模板以推断列表嵌套的次数?
  • std::initializer_list有比这种情况更好的选择吗?
4

1 回答 1

4

您可以在 SFINAE和SFINAE的帮助下编写两个重载constexpr 函数模板来计算嵌套时间。std::enable_if

// types have not member type value_type
template <typename T, typename = void>
struct has_value_type: std::false_type {};
// types have member type value_type
template <typename T>
struct has_value_type<T, std::void_t<typename T::value_type>> : std::true_type {};

// return nested times as 0 for types without member type value_type
template<typename T>
constexpr std::enable_if_t<!has_value_type<T>::value, size_t> get_nested_times() {
    return 0;
}
// return nested times as 1 plus times got on the nested type recursively
template<typename T>
constexpr std::enable_if_t<has_value_type<T>::value, size_t> get_nested_times() {
    return 1 + get_nested_times<typename T::value_type>();
}

然后你可以在编译时获得嵌套时间

template<typename List>
auto some_function (const List& list)
{
    // N is the number of times the list is nested.
    constexpr auto N = get_nested_times<List>();
    std::array<size_t, N> arr;
    return arr;
}

居住

于 2020-03-09T11:43:12.390 回答