typedefing非类型模板参数

时间:2013-02-10 15:31:14

标签: c++ templates

我想访问类外的模板参数。我通常这样做:

template <class T>
class A
{
  typedef typename T T;
}

A<int>::T;

我希望能够对非类型模板参数执行相同的操作。这不起作用:

template <int T>
class A
{
  typedef typename T T;
}

A<3>::T;

我将澄清为什么我需要这个。我想按如下方式定义第二个类:

template <class C>
class B
{
  static int func() {return C::T;}
}

B<A<3> >::func();

这样做的正确方法是什么? 非常感谢你。

3 个答案:

答案 0 :(得分:5)

那是因为T不是类型名称而你不能typedef。它是int值,如果要将其作为类的静态成员访问,则需要静态成员int。看起来你真正想要的是这个:

template <int T>
class A
{
  public:
    static const int x = T;
};

doSomething(A<5>::x);

答案 1 :(得分:2)

它是一个值,而不是一个类型,所以也许:

template <int T>
class A
{
  static const int param = T;
};

然后您可以A<42>::param访问它。并非它有多大帮助,除非A本身在其他地方用作模板参数。

答案 2 :(得分:1)

在第二种情况下,T不是类型,它是int值。因此,您应将其定义为 const int static const int值。

template <int T>
class A {
    static const int T = T;
};

请注意,习惯使用T表示类型(特别是当模板是monadic时,因为类型没有歧义),以及常量的其他名称,通常是更有意义的名称,例如SIZE或最好Size(所有大写符号最适合用于宏)。

template <int Param>
class A {
    static const int param = Param;
};

有关在模板定义的上下文中使用static const值,请参阅其他SO问题(例如this one)。

相关问题