【发布时间】: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 不是,导致'使用未定义类型'。
不过,我已经读到,将嵌套在类模板中的类模板特化是不行的。为什么它在这里工作?如果我想提供这种行为(匹配外部模板参数)有什么更好的方法?
【问题讨论】:
-
一个要求是 Inner2 的模板类型参数必须仍然能够变化。
标签: c++ visual-studio templates template-meta-programming template-specialization