typename 参数的模板专用化是特定模板的任何实例化

Template specialization on typename parameter being any instantiation of a particular template

本文关键字:任何 实例化 专用 参数 typename      更新时间:2023-10-16

我有一个类模板Z,当传递一个类型时,我想专门化一个类型,该类型是特定模板的任何实例化N

struct L {
    template <typename S> void foo(S &) {/*...*/}
};
template <class T>
struct M {
    template <typename S> void foo(S &) {/*...*/}
};
template <class T>
struct N {
    template <typename S> void foo(S &) {/*...*/}
};
// I'd like to specialize this for TY==N<anything>
template <typename TX, typename TY>
struct Z {
    void bar(TX &tx) { /*...*/ ty->foo(tx); /*...*/ }
    TY *ty;
};

由于Z<int, L>Z<int, N<int>>Z<int, M<int>>都是有效的用例,因此我无法做任何事情将Z转换为模板模板,并且当TY是从N构建的类时,Z<TX, TY>::bar(TX &)可能会降低引人注目的复杂性。 有没有办法实现这一目标?

这应该会影响您想要的专业化:

template <typename TX, typename ANY>
struct Z< TX, N<ANY> > {
    // ...
};

当第一个参数TX,第二个参数N<ANY>时,Z变得专用。快速说明:

template <typename A> struct N { A a; };
template <typename TX, typename TY>
struct Z { Z () { std::cout << "not special" << std::endl; } };
template <typename TX, typename ANY>
struct Z< TX, N<ANY> > { Z () { std::cout << "special" << std::endl; } };
int main ()
{
    Z<int, int> z1;
    Z<int, N<int> > z2;
}

输出结果:

not special
special