【问题标题】:Template class inheritance from a different specialization来自不同专业化的模板类继承
【发布时间】:2013-07-10 13:17:19
【问题描述】:

这是一个出于对 C++ 规则的好奇而没有任何实际用途的问题。在玩弄模板时,我创建了一个类层次结构,如下所示:

#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;
}

这段代码在 Visual Studio 上编译得很好并产生了预期的输出:

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

这是一种有效的 C++ 设计实践吗?这对我来说确实很奇怪,所以我想知道这是否是某种未定义的行为,它恰好取决于编译器,有很多陷阱和陷阱,或者它是否是模板的定义明确的用法。

看看这方面的任何实际例子会很有趣。

【问题讨论】:

  • 没有未定义的行为。它按预期工作。模板实例化可以派生自另一个模板实例化(请记住,同一模板的两个单独实例化是两个单独的类)。例如,当且仅当X != 0 时,这允许您拥有一个具有bar() 函数的A&lt;X&gt;

标签: c++ templates inheritance specialization


【解决方案1】:

这是一种在递归定义template 时经常使用的标准技术。

这种技术的一个例子是整数序列:

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

尤其是在他们这一代:

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...> {};

通过从template 的不同实例继承简单而递归地描述。

明确地说,make_seq&lt;7&gt;::typeseq&lt;0,1,2,3,4,5,6&gt;,通过 7 级递归继承。

【讨论】:

    【解决方案2】:

    就 C++ 而言,这是有效的。类模板 A&lt;1&gt; 与另一个类模板 A&lt;0&gt; 是完全不同的动物。

    实际上,您在此处构建的内容看起来类似于所谓的Curiously Recurring Template Pattern

    【讨论】:

      猜你喜欢
      • 2017-01-05
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多