c++ - 为具有不同模板参数的模板部分特化模板类

标签 c++ templates template-specialization

如何让一个类模板接受另一个可能具有两个不同参数列表之一的类模板?即,一个非类型参数或一个类型和非类型参数:

template <int X>
struct Foo1{};

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

我希望能够将这些模板中的任何一个传递到我的模板(以及跟随他们脚步的 future 模板)。我希望这说明了我所追求的,尽管语法完全错误:

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

我想不出一种方法来为这些编写特化。如果不可能,我可以有 Foo1并且所有类似的模板都有一个不执行任何操作的模板类型参数(template <typename, int X> Foo1{};)并编写Magic考虑到这一点,但我希望有一个更优雅的解决方案。

最佳答案

您可以应用的一种解决方案是为每个不同类模板的声明引入包装器,并根据包装器包装的内容专门化神奇的结构。最终,您唯一需要知道的是哪个包装器与哪个类模板相关联。

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

关于c++ - 为具有不同模板参数的模板部分特化模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33975389/

相关文章:

php - PHP注入(inject)HTML中的switch语句

C++ 结构指针指向对象类型错误

c++ - Qt - QWebView问题

c++ - 无操作函数模板

c++ - 简化大量模板特化

c++ - 成员模板变量特化

c++ - sizeof... 是否允许在模板参数中用于特化?

c++ - OpenGL 奇怪的渲染行为(闪烁的面孔)

c++ - 如果我发现这个声明有任何异常(exception),请告诉我

templates - Drupal 8 获取内容并在没有页眉/页脚的情况下提供服务