在派生类中使用基类的模板参数 [英] Using template argument of base class in derived class

查看:163
本文介绍了在派生类中使用基类的模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑C ++中的以下情况:

Consider the following situation in C++:

template<int n>
class Base { ... };

class Derived3 : public Base<3> {
  // a complicated body, making use of n=3
};

class Derived7 : public Base<7> {
  // a completely different body, making use of n=7
};

Derived3成员函数内部,我想显式地使用n=3,在Derived7n=7内部,而无需对数字进行硬编码,即仍然引用诸如模板参数n之类的东西. .我想到以下选择:

Inside of the Derived3 member functions, I would like to explicitly use n=3, and inside Derived7, n=7, without hardcoding the numbers, i.e., still referring to something like a template argument n. The following options come to my mind:

  1. 还要在n上对派生类进行模板化,然后使用typedef.这样,派生类就知道n:

  1. Also templating the derived classes on n, and then using typedef. This way, the derived classes know n:

template<int n>
class DerivedTemplate3 : public Base<n> { ... };
typedef DerivedTemplate3<3> Derived3;

template<int n>
class DerivedTemplate7 : public Base<n> { ... };
typedef DerivedTemplate7<7> Derived7;

问题是DerivedTemplateX除了n=X之外什么都没有,所以就好像在滥用模板范式.

The problem with this is that DerivedTemplateX makes sense for nothing but n=X, so this feels like abusing the template paradigm.

使用静态const成员将n存储在Base中,并在派生类中进行引用:

Using a static const member to store n in Base, and referring to that in the derived classes:

template<int n>
class Base {
protected:
  static const int nn = n;
  ...
};

class Derived3 : public Base<3> {
  // refer to nn=3
};

class Derived7 : public Base<7> {
  // refer to nn=7
};

这里的问题是我似乎无法使用相同的标识符(nnn).另外,我不确定这是否允许我将nn用作派生类成员的模板参数.

The problem here is that I seemingly can't use the same identifier (nn vs. n). Also, I'm not sure whether this will allow me to use nn as a template argument for members of the derived classes.

那么:如何以一种非冗余,有效的方式来实现呢?也许在某处使用某种static const int作为成员?

So: how can this be implemented in a non-redundant, efficient way? Maybe using some kind of static const int as a member somewhere?

推荐答案

标准做法是对模板参数使用大写字母,然后对小写字母使用静态const值:

The standard practice is to use an uppercase letter for the template parameter, then a static const value in lowercase:

template<int N>
class Base {
protected:
  static const int n = N;
  ...
};

然后在所有地方都使用小写的静态const值n-在其他任何地方都不要使用N.

Then you use the lowercase static const value n everywhere - don't use N anywhere else.

此外,我不确定这是否允许我将nn用作派生类成员的模板参数.

Also, I'm not sure whether this will allow me to use nn as a template argument for members of the derived classes.

这是一个常量表达式,因此可以用作模板参数.

It is a constant expression and so it can be used as a template argument.

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

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