如果模板参数AA是一个模板化的class A<T>本身,是否可以得到这个模板化的class的模板参数(T)?

If template parameter AA is a templatized class A<T> itself, is it possible to get the template parameter (T) of this templatized class?

考虑以下代码:

template <typename T>
class A{
...
}

template <class U>
class B{
...
}

int main {
B<A<int>> a;
...
}

如果 A 是 B 的模板参数,如何在 B 中获取 A 的模板参数(本例中为 int)? 我可以按如下方式对 B 进行参数化,但我觉得我发送了一条不必要的信息。

template <class AA, typename T>
class B { ... }

我不简单地对class B 使用template <typename T> 的原因是我在B 中有一个指向class A 的指针,我想使用模板参数class AA 以查看该指针是否为 const,因此具有 B 中成员指针的正确类型。

我认为以下内容符合您的要求:

#include<type_traits>
template<class>
class A{};

template<class>
struct get_inner;

template<template<class> class TT, class T>
struct get_inner<TT<T>> {
    using outer = TT<T>;
    using inner = T;
};

template<class TT>
struct B {
    using A = TT;
    using inner = typename get_inner<std::decay_t<A>>::inner;
};


int main(int argc, char *argv[])
{
    static_assert(std::is_const_v<typename B<const A<int>>::A>);
        static_assert(!std::is_const_v<typename B<A<int>>::A>);
}

请注意 std::decay_t,它不能直接与 const 参数一起使用(因此我们不能仅以这种方式专门化 B)。也许 decay_t 有点强,但它有效^^

试试这个

template <typename X> class B;

template <template <typename> class XX, typename T>
class B<XX<T>>
{
    // your implementation
};

B<A<int>> a;

有几种方法,具体取决于您可能会更改的方法:

  • 快捷方式,专精B

    template <class> class B;
    
    template <class T>
    class B<A<T>>
    {
        // Use directly T
        //...
    };
    
  • 直接在 A 中添加信息(就像 std 容器对 value_type 所做的那样)

    template <typename T>
    struct A
    {
        using my_type = T;
    };
    
    // Then in `B<U>`, use `typename U::my_type`
    
  • 使用外部特征从 A 中提取信息(如 std::iterator_traits)(也允许处理内置类型):

    template <typename T>
    struct ATrait;
    
    template <typename T>
    struct ATrait<A<T>>
    {
        using my_type = T;
    };
    
    // Possibly a generic one
    template <template <typename> class C, typename T>
    struct ATrait<C<T>>
    {
        using my_type = T;
    };
    
    // Then in `B<U>`, use `typename ATrait<U>::my_type`