简体   繁体   English

来自不同专业的模板类继承

[英]Template class inheritance from a different specialization

This is a question out of curiosity on C++ rules without any real practical usage. 这是一个问题,出于对C ++规则的好奇而没有任何实际的用法。 When toying around with templates, I created a class hierarchy like so: 在使用模板进行操作时,我创建了一个类层次结构,如下所示:

#include <stdio.h>

// Declaration
template <int X = 0>
struct A;

// Specialization for X = 0
template <>
struct A<0>
{
    virtual void foo()
    {
        printf("A<0>::foo()\n");
    }
};

// Extended generalized implementation
template <int X>
struct A : public A<0>
{
    virtual void foo()
    {
        printf("A<1>::foo()\n");
    }

    virtual void bar()
    {
        printf("A<1>::bar()\n");
    }
};

int main()
{
    A<> a0;
    A<1> a1;

    a0.foo();
    a1.foo();
    a1.bar();

    return 0;
}

This code compiled fine on Visual Studio and produces the expected output: 此代码在Visual Studio上编译良好并生成预期输出:

A<0>::foo()
A<1>::foo()
A<1>::bar()

Is this a valid C++ design practice? 这是一个有效的C ++设计实践吗? It certainly looks strange to me, so I'm wondering if this is some sort of undefined behaviour which just happens to work depending on compiler with lots of pitfalls and gotchas, or if it is a well-defined usage of templates. 它当然看起来很奇怪,所以我想知道这是否是某种未定义的行为,它恰好依赖于具有许多陷阱和陷阱的编译器,或者如果它是一个明确定义的模板用法。

It would be interesting to see any practical examples of this. 看到任何实际的例子都会很有趣。

This is a standard technique that is quite often used when defining a template recursively. 这是一种在递归定义template时经常使用的标准技术。

An example of such a technique would be sequences of integers: 这种技术的一个例子是整数序列:

template<int...s> struct seq {typedef seq<s...> type;};

In particular, in their generation: 特别是在他们这一代:

template<int max, int... s> struct make_seq:make_seq<max-1, max-1, s...> {};
template<int... s> struct make_seq<0, s...>:seq<s...> {};

which is described recursively and simply by inheriting from a different instantiation of the template . 通过继承template的不同实例来递归地描述。

To be explicit, make_seq<7>::type is seq<0,1,2,3,4,5,6> via 7 levels of recursive inheritance. 显而易见, make_seq<7>::typeseq<0,1,2,3,4,5,6>通过7级递归继承。

This is valid as far as C++ is concerned. 就C ++而言,这是有效的。 A class template A<1> is an entirely different animal from another class template A<0> . 类模板A<1>是与另一类模板A<0>完全不同的动物。

In fact, what you have built here looks similar to what is called the Curiously Recurring Template Pattern . 实际上,您在此处构建的内容与所谓的奇怪重复模板模式类似。

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

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