这样做更好吗:
const int MY_CONST = 20; // global constant in the program
class A {
// uses MY_CONST all over the class implementation and definition
}
还是这个?
const int MY_CONST = 20; // global constant in the program
template<int my_const>
class A {
//uses my_const only and never MY_CONST
};
//A<MY_CONST> used later in the program
其中一种模式比另一种更好吗?为什么? 谢谢
最佳答案
除非该全局常量在类之外的其他地方使用,否则我不会使用这两种方法并使该常量成为 A
的成员:
class A {
public:
static const int MY_CONST = 20;
};
const int A::MY_CONST; // Possibly need definition also
然后在代码中使用 A::MY_CONST
。
我唯一使用模板的时候是当您出于某种原因需要根据实例更改值时。
template <int I>
class A
{
public:
static const int MY_CONST = I;
};
template <int I>
const int A<I>::MY_CONST; // Definition
然后像这样创建实例:
A<1> a1;
A<2> a2;
关于c++ - 用模板参数替换常量是不是更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12307561/