【发布时间】:2020-10-01 11:22:28
【问题描述】:
我正在寻找一种递归替换模板中的类型的方法。更具体地说,将T[N] 变成std::array<T, N>。如果包含非类型模板参数,问题是递归执行此操作。
目前,我有以下代码:
template<typename T>
struct replaced {
using type = T;
};
template<typename T, std::size_t N>
struct replaced<T[N]> {
using type = std::array<typename replaced<T>::type, N>;
};
template<template<typename...> typename T, typename... Ts>
struct replaced<T<Ts...>> {
using type = T<typename replaced<Ts>::type...>;
};
没有非类型模板参数的测试用例可以正常工作,但是一旦引入了非类型模板参数,它就不再起作用了:
// this works (simple replacement)
static_assert(std::is_same_v<replaced<int[3]>::type, std::array<int, 3>>);
// this also works (nested types)
static_assert(std::is_same_v<
replaced<std::tuple<int[2], std::pair<int, float[3]>>>::type,
std::tuple<std::array<int, 2>, std::pair<int, std::array<float, 3>>>>);
// this doesn't work (non-type template parameters)
static_assert(std::is_same_v<
replaced<std::array<int[2], 2>>::type,
std::array<std::array<int, 2>, 2>>);
// instead this works, but shouldn't
static_assert(std::is_same_v<
replaced<std::array<int[2], 2>>::type,
std::array<int[2], 2>>);
我了解可变参数模板模板参数不适用于非类型模板参数。有什么方法可以修改replaced 的定义来实现我的目标?
【问题讨论】: