我正在尝试构建编译时表。我使用数组数组...来做到这一点。遗憾的是,编译器无法推断出结果类型的模板参数。有工作吗?
#include <array>
template <typename T, size_t... dims>
struct variadic_array;
template <typename T, size_t... dims>
using variadic_array_t = typename variadic_array<T, dims...>::type;
template <typename T, size_t dim>
struct variadic_array<T, dim> {
using type = std::array<T, dim>;
};
template <typename T, size_t dim, size_t ...dims>
struct variadic_array<T, dim, dims...> {
using type = std::array<variadic_array_t<T, dims...>, dim>;
};
template <typename T, size_t ...dims>
void foo(variadic_array_t<T, dims...>) {}
void call_foo() {
foo(variadic_array_t<int, 3, 4>{});
}
编译错误:
error: no matching function for call to 'foo'
foo(variadic_array_t<int, 3, 4>{});
^~~
note: candidate template ignored: couldn't infer template argument 'T'
void foo(variadic_array_t<T, dims...>) {}
^
答案 0 :(得分:1)
T
无法从C<T>::type
推断出(非演绎语境)。
您可以通过传递简单模板T
并从中检索信息来解决问题:
// Helpers
template <typename T> struct is_std_array : std::false_type {};
template <typename T, std::size_t N>
struct is_std_array<std::array<T, N>> : std::true_type {};
template <typename T> struct identity { using type = T; };
// The trait
template <typename T, std::size_t...> struct variadic_array_traits;
template <typename T, std::size_t N, std::size_t ... dims>
struct variadic_array_traits<std::array<T, N>, dims...>
{
using type =
typename std::conditional_t<is_std_array<T>::value,
variadic_array_traits<T, dims..., N>,
identity<variadic_array<T, dims..., N>>>::type;
};
// For SFINAE
template <typename ... >
using void_t = void;
// Your method
template <typename T>
void_t<typename variadic_array_traits<T>::type>
foo(T)
{
using variadic_array_type = typename variadic_array_traits<T>::type;
// ...
}