Gui*_*cot 1 c++ templates template-meta-programming c++20
我有一个名为 的类型the_bad
。the_good
我想用模板元函数替换该类型。我预计该模板元函数会非常复杂,因此我们将其称为the_ugly
.
我的问题是它the_bad
可以嵌套在其他模板中,并且我想保持其他模板和参数不变。这是我的意思的一个例子,其中的实现不完整the_ugly
:
struct the_good {};
struct the_bad {};
template<typename T>
struct the_ugly_impl {
using type = T;
};
template<>
struct the_ugly_impl<the_bad> {
using type = the_good;
};
template<typename T>
using the_ugly = typename the_ugly_impl<T>::type;
// passes, yay!
static_assert(std::same_as<the_good, the_ugly<the_bad>>);
// doesn't pass
static_assert(std::same_as<std::vector<the_good>, the_ugly<std::vector<the_bad>>>);
// doesn't pass
static_assert(std::same_as<std::list<std::vector<the_good>>, the_ugly<std::list<std::vector<the_bad>>>>);
Run Code Online (Sandbox Code Playgroud)
我该如何修复,the_ugly
以便它在任何嵌套级别替换the_bad
为,同时保持所有其他模板和其他模板参数不变?the_good
You just need to handle the template case, and have that invoke itself recursively:
template<typename T>
struct the_ugly_impl {
using type = T;
};
template<typename T>
using the_ugly = typename the_ugly_impl<T>::type;
template<>
struct the_ugly_impl<the_bad> {
using type = the_good;
};
template <template <typename...> class L, typename... Ts>
struct the_ugly_impl<L<Ts...>> {
using type = L<the_ugly<Ts>...>;
};
Run Code Online (Sandbox Code Playgroud)