简体   繁体   English

部分专门化具有不同模板参数的模板的模板类

[英]Partially specialize template class for templates with different template parameters

How can I get a class template to accept another class template that could have one of two different parameter lists? 如何让类模板接受另一个可能具有两个不同参数列表之一的类模板? Namely, a non-type parameter or a type and non-type parameter: 即,非类型参数或类型和非类型参数:

template <int X>
struct Foo1{};

template <typename T, int X>
struct Foo2{};

I want to be able to pass either of these templates to my template (plus future templates that follow in their footsteps). 我希望能够将这些模板中的任何一个传递给我的模板(以及跟随其后脚步的未来模板)。 I hope this illustrates what I'm after, although the syntax is all wrong: 我希望这能说明我所追求的内容,尽管语法完全错误:

template <typename T, int X, class>
struct Magic; //Don't accept non template parameters

template <typename T, int X, class <int> class C>
struct Magic<T, X, C> {}; //Template non-type

template <typename T, int X, class <class, int> class C>
struct Magic<T, X, C> {}; //Template type and non-type

I can't think of a way to write a specialization for these. 我想不出为这些编写专业化的方法。 If it isn't possible, I can just have Foo1 and all templates like it have a template type parameter that doesn't do anything ( template <typename, int X> Foo1{}; ) and write Magic with that in mind, but I was hoping for a more elegant solution. 如果不可能,我可以只有Foo1 ,所有类似的模板都有一个模板类型参数,它没有做任何事情( template <typename, int X> Foo1{}; )并且考虑到了Magic ,但是我希望有一个更优雅的解决方案。

One solution you could apply is to introduce wrappers for each distinct class template's declaration, and specialize the magical structure based on what the wrapper wraps. 您可以应用的一个解决方案是为每个不同的类模板声明引入包装器,并根据包装器包装的内容专门设置神奇的结构。 Eventually the only thing you need to know is which wrapper is associated with which class template. 最后,您唯一需要知道的是哪个包装器与哪个类模板相关联。

template <int X>
struct Foo1{};

template <typename T, int X>
struct Foo2{};

template <template <int> class C> struct W1;

template <template <class, int> class C> struct W2;

template <typename T, int X, class>
struct Magic; //Don't accept non template parameters

template <typename T, int X, template <int> class C>
struct Magic<T, X, W1<C> > {}; //Template non-type

template <typename T, int X, template <class, int> class C>
struct Magic<T, X, W2<C> > {}; //Template type and non-type

int main()
{
    Magic<int, 1, W1<Foo1> > m1;
    Magic<int, 2, W2<Foo2> > m2;
}

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM