在 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
的内容。我想到以下选项:
还在
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
之外什么都没有意义,所以这感觉就像在滥用模板范例。使用静态 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 };
这里的问题是我似乎不能使用相同的标识符(
nn
与n
)。另外,我不确定这是否允许我使用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/