如何在任何嵌套级别替换模板中的类型?

Gui*_*cot 1 c++ templates template-meta-programming c++20

我有一个名为 的类型the_badthe_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

Bar*_*rry 5

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)

  • 非类型模板参数已加入聊天:( 无论如何都已更新 (2认同)
  • @StoryTeller-UnslanderMonica 是的,我有点明白你的意思了。我想这样就可以了。我可以处理一些常见的情况,然后就到此为止了 (2认同)