【问题标题】:Understanding an Implicit Instantiation of Class Template Specialization Example了解类模板专业化示例的隐式实例化
【发布时间】:2017-12-14 13:53:34
【问题描述】:

所以标准的this section 给出了这个例子(我的问题是内联的):

template<class T, class U>
struct Outer {
    template<class X, class Y> struct Inner;      // Where are X and Y from? Is this defining a struct?
    template<class Y> struct Inner<T, Y>;         // Is this defining a struct specialization? If so what is Y?
    template<class Y> struct Inner<T, Y> { };     // I feel like this is a redefinition of the line above, could it ever not be?
    template<class Y> struct Inner<U, Y> { };
};

诚然,我无法理解标准的链接部分,因为我无法理解这里发生了什么。我想我只是被所有templates 飞来飞去弄糊涂了,但是如果有人可以逐行告诉我发生了什么,那将非常有帮助。

【问题讨论】:

  • @Downvoter 我知道这被标记为 C++。您只是在 C++ 问题上提供了强制性的否决票,还是这个问题实际上有问题?

标签: c++ metaprogramming declaration definition template-specialization


【解决方案1】:
template<class X, class Y> struct Inner;      
// Where are X and Y from? Is this defining a struct?

这是模板结构InnerXY的声明,是模板参数。

template<class Y> struct Inner<T, Y>;         
// Is this defining a struct specialization? If so what is Y?

这是部分特化的声明,Y 是模板参数。

template<class Y> struct Inner<T, Y> { };     
// I feel like this is a redefinition of the line above, could it ever not be?

这是偏特化的定义,这里不再重新定义。

然后将它们用作:

Outer<foo1, foo2>::Inner<foo3, foo4>* i1; 
// the primary template is used, with T=foo1, U=foo2, X=foo3, Y=foo4
// btw the primary template is not defined in this example

Outer<foo1, foo2>::Inner<foo1, foo3> i2; 
// the 1st partial specialization is used, with T=foo1, U=foo2, Y=foo3

Outer<foo1, foo2>::Inner<foo2, foo3> i3; 
// the 2st partial specialization is used, with T=foo1, U=foo2, Y=foo3

【讨论】:

  • 我们真的可以这样做吗:Outer&lt;foo1, foo2&gt;::Inner&lt;foo3, foo4&gt; i1;?是这样定义的吗?
【解决方案2】:

给你:

template<class T, class U>
struct Outer {
    // Forward-declares a struct with two template parameters
    template<class X, class Y> struct Inner;

    // Forward-declares a partial specialization of Inner
    // (Y is its only template parameter)
    template<class Y> struct Inner<T, Y>;

    // Defines the forward-declared partial specialization
    template<class Y> struct Inner<T, Y> { };

    // Declares and defines another partial specialization
    // (Y is its only template parameter)
    template<class Y> struct Inner<U, Y> { };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2021-11-25
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    相关资源
    最近更新 更多