c++ - 在派生类中使用基类的模板参数

标签 c++ templates polymorphism

在 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,在 Derived7 内部,n= 7,没有对数字进行硬编码,即,仍然引用类似模板参数 n 的内容。我想到以下选项:

  1. 还在 n 上模板派生类,然后使用 typedef。这样,派生类就知道 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 之外什么都没有意义,所以这感觉就像在滥用模板范例。

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

    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 作为派生类成员的模板参数。

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

最佳答案

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

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

然后你在任何地方都使用小写的静态常量值 n - 不要在其他任何地方使用 N

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

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

关于c++ - 在派生类中使用基类的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14435710/

相关文章:

c++ - GCC 中的通用 lambda

c++ - std::rel_ops 功能作为基类。那是合适的解决方案吗?

c++ - 访问子类变量的正确解决方案是什么?

c++ - 是否可以在 gcc 中关闭对 "and"/"or" boolean 运算符使用的支持?

c++ - 循环包含和前向声明类

c++ - 代码审查问题——我应该允许将 auto_ptr 作为参数传递吗?

c++ - C和C++中引用传递的含义?

c++ - ios项目的预链接静态库

c++ - 将指向派生类指针的指针作为参数传递给期望指向基类指针的构造函数

c# - 不完全确定如何使用接口(interface)进行多重继承 c#