【问题标题】:Nested class template specialization not matched correctly + msvc internal error嵌套类模板特化未正确匹配 + msvc 内部错误
【发布时间】:2015-12-07 05:29:32
【问题描述】:

这个问题由两部分组成,标记为 (A) 到 ...ahem... (C)。

template< unsigned a > struct Outer {
    /*
(A)    Provide a match if the template parameter of Inner is the same
       as Outer.  Do something different in the general case (not shown)
    */
    template< unsigned b > struct Inner1;
    template<> struct Inner1<a> { enum { value = a }; };

    /*
(B)    Same idea as (A), but we want an additional template parameter
    */
    template< typename T, unsigned b > struct Inner2;
    template< typename T > struct Inner2< T, a > { enum { value = a }; };

    typedef Inner1<a> Result1;
    typedef Inner2<int, a> Result2;
};

// (C) Alternative way of defining our specializations?
template< unsigned a > template<> 
struct Outer<a>::template Inner1<a> {};

template< unsigned a > template< typename T >
struct Outer<a>::template Inner2<T, a> {};

void code() {
   Outer<1>::Result1::value; // OK, 
   Outer<1>::Result2::value; // error C2027: use of undefined type 'Outer<1>::Inner2<int,1>'
}

使用 Visual Studio 2013 或 2015,没有语言扩展,(A) 和 (B) 编译成功。 (C) 以fatal error C1001: An internal error has occurred in the compiler. 帮助失败

(A) Result1 被正确选择为专用模板

(B) Result2 不是,导致'使用未定义类型'。

不过,我已经读到,将嵌套在类模板中的类模板特化是不行的。为什么它在这里工作?如果我想提供这种行为(匹配外部模板参数)有什么更好的方法?

(C)I guess this is a case of "Don't do that..."

【问题讨论】:

  • 一个要求是 Inner2 的模板类型参数必须仍然能够变化。

标签: c++ visual-studio templates template-meta-programming template-specialization


【解决方案1】:

这是完成案例(B)的一种方法。

template< typename T, unsigned b, unsigned a > struct Inner;
template< typename T, unsigned a >
struct Inner< T, a, a > { enum { value = a }; };

template< unsigned a > struct Outer {
    typedef Inner<int, a, a> Result;
};

void code() {
    Outer<1>::Result::value; // OK, 
}

唯一的限制是 Inner 不能再位于原始类的私有部分(例如,如果它是 Outer 的实现细节,因此应该具有受限的访问权限)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    相关资源
    最近更新 更多