考虑下面的类:
class Foo
{
enum Flags {Bar, Baz, Bax};
template<Flags, class = void> struct Internal;
template<class unused> struct Internal<Bar, unused> {/* ... */};
template<class unused> struct Internal<Baz, unused> {/* ... */};
template<class unused> struct Internal<Bax, unused> {/* ... */};
};
在 VC++ 2010 和 Comeau C++ 上测试时,上面的类大纲可以按预期编译和运行。然而,当Foo
本身制作成模板,上面的代码片段在 VC++ 2010 下会中断。
例如,以下代码片段:
template<class> class Foo
{
// Same contents as the original non-templated Foo.
};
产生以下结果错误等级 http://msdn.microsoft.com/en-us/library/sa66t7aa.aspx:
C2754: 'Foo<<unnamed-symbol>>::Internal<Bar,unused>' : a partial specialization cannot have a dependent non-type template parameter
C2754: 'Foo<<unnamed-symbol>>::Internal<Baz,unused>' : a partial specialization cannot have a dependent non-type template parameter
C2754: 'Foo<<unnamed-symbol>>::Internal<Bax,unused>' : a partial specialization cannot have a dependent non-type template parameter
- 有人能用简单的英语解释这里发生了什么吗?
- 我该如何解决这个问题(即,将内部伪显式专业化保留在模板化中)
Foo
)在 VC++ 2010 上?
如何在 VC++ 2010 上解决此问题(即在模板化 Foo 中保留内部伪显式专业化)?
您可以通过在非模板基类中声明枚举类型来使其不依赖(C++03 使嵌套类依赖于#108 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#108但这不包括枚举,但即使如此,这样的代码仍然是合法的)。
struct FooBase {
enum Flags {Bar, Baz, Bax};
};
template<class> class Foo : public FooBase {
template< ::FooBase::Flags, class = void > struct Internal;
// same other stuff ...
};
“错误类”链接已经给出了应该出现错误的预期情况的描述。该错误认为所有依赖类型都是被禁止的,但实际上标准是这样说的:
与专门化的非类型参数相对应的模板参数的类型不应依赖于专门化的参数。
所以即使名字Flags
会以某种方式依赖,只要它不依赖于专业化的参数(如“错误类”链接的示例中所示),就不会使其格式错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)