如何在不使用额外模板参数的情况下使用模板模板参数声明/定义类

Aut*_*act 3 c++ templates metaprogramming

考虑以下模板模板参数的使用......

#include <iostream>

template <typename X>
class A
{
    X _t;
public:
    A(X t)
        :_t(t)
    {
    }
    X GetValue()
    {
        return _t;
    }
};

template <typename T, template <typename T> class C >
class B
{
    C<T> _c;
public:
    B(T t)
        :_c(t)
    {
    }
    T GetValue()
    {
        return _c.GetValue();
    }
};

using namespace std;

int main()
{
    B<int, A> b(10);
    cout<<b.GetValue();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法可以删除模板参数T?例如,是否有办法进行以下工作?

//Does not compile
template <template <typename T> class C >
class B
{
    C _c;
public:
    B(T t)
        :_c(t)
    {
    }
    T GetValue()
    {
        return _c.GetValue();
    }
};

int main()
{
    B< A<int> > b(10);
    cout<<b.GetValue();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 8

我假设您在代码中使用X和A之后.

通常的模式是

template<typename C>
struct B
{
   C c;
};
Run Code Online (Sandbox Code Playgroud)

然后,在符合替代条件的内部课程中:

template<typename X>
class A
{
   typedef X type_name;
   X t;
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用访问模板参数C::type_name.