【问题标题】:C++ template comprehensionC++ 模板理解
【发布时间】:2011-10-06 06:30:49
【问题描述】:

我试图理解以下代码的含义,因为它是有效的 C++ 代码:

template<class A>
class AT
{
    AT();
};

template<class B>
AT<B>::AT()
{}

谁能帮我理解模板实例化在构造函数中的作用是什么?如果有人能提供一个有用的实际用例,我将不胜感激。

坦克

【问题讨论】:

    标签: c++ templates semantics


    【解决方案1】:

    这里没有模板实例化。这段代码的后半部分简单地定义了AT 类的构造函数。请注意,执行此操作时,一般做法是为模板参数使用相同的名称:

    template<class A>
    class AT
    {
        AT();
    };
    
    template<class A>
    AT<A>::AT()
    {}
    

    这种语法的用途是打破依赖循环:

    template<class A>
    class AT
    {
        AT();
    };
    
    class Dependent
    {
        AT<Dependant> member; // Complete definition of AT is needed here
    };
    
    template<class A>
    AT<A>::AT()
    {
        Dependent object; // Complete definition of Dependent is needed here
    }
    

    【讨论】:

    • 好的,但是模板 是什么意思呢?
    • 模板的声明或定义遵循...?
    【解决方案2】:

    模板参数的名称并不重要。如果你把第二部分写成

    template<class A>
    AT<A>::AT()
    { }
    

    魔法消失了,它只是构造函数的定义。

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 1970-01-01
      • 2013-04-16
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多