相关的非类型模板参数 [英] Dependent Non-Type Template Parameters

查看:41
本文介绍了相关的非类型模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下类:

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 下会中断.

The class outline above compiles and functions as expected when tested on VC++ 2010 and Comeau C++. However, when Foo is made into a template itself, the above snippet breaks under VC++ 2010.

例如,以下代码段:

template<class> class Foo
{
  // Same contents as the original non-templated Foo.
};

产生以下错误类别:

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

<小时>

  1. 有人可以用简单的英语解释这里发生的事情吗?
  2. 如何在 VC++ 2010 上解决此问题(即,在模板化的 Foo 中保留内部伪显式特化)?
  1. Can someone explain what is going on here in plain English?
  2. How can I fix this (i.e., keep internal pseudo-explicit specializations in a templated Foo) on VC++ 2010?

推荐答案

如何在 VC++ 2010 上解决此问题(即,在模板化 Foo 中保留内部伪显式特化)?

How can I fix this (i.e., keep internal pseudo-explicit specializations in a templated Foo) on VC++ 2010?

您可以通过在非模板基类中声明枚举类型来使其不依赖(C++03 使嵌套类依赖于 #108 但这不包括枚举,但即使这样,这样的代码仍然是合法的).

You can make the enumeration type non-dependent by declaring it in a non-template base class (C++03 made nested classes dependent in #108 but that doesn't include enumeration, but even if, such code would still be legal).

struct FooBase { 
  enum Flags {Bar, Baz, Bax};
};

template<class> class Foo : public FooBase {
  template< ::FooBase::Flags, class = void > struct Internal;
  // same other stuff ...
};

错误类"链接已经给出了应该出现错误的预期情况的描述.错误认为禁止所有依赖类型,但实际上这是标准所说的:

The "error class" link already gives a description of the intended cases where the error should be risen. The error thinks that all dependent types are forbidden, but in fact this is what the Standard says:

与特化的非类型实参对应的模板形参的类型不应依赖于特化的参数.

The type of a template parameter corresponding to a specialized non-type argument shall not be dependent on a parameter of the specialization.

因此,即使名称 Flags 会以某种方式依赖,只要它不依赖于像您的示例中那样的专业化参数,也不会使其格式错误错误类"链接.

So even if the name Flags would be somehow dependent, that wouldn't make it ill-formed as long as it doesn't depend on a parameter of the specialization like in the example of your "error class" link.

这篇关于相关的非类型模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆