c++ - 用模板参数替换常量是不是更好?

标签 c++ templates

这样做更好吗:

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/

相关文章:

templates - TYPO3 7.1 felogin 模板文件无法通过 TypoScript 工作

c++ - C++ 错误 : redefinition of class constructor using templates

c++ - 模板变量的显式特化

c++ - 如何使用最少的代码 C++ 设置数组的特定元素

c++ opengl我如何制作着色器文件并在主cpp中使用它

c++ - 从 HBITMAP 转换为 IWICBitmap

c++ - 结构中的类型注入(inject)

c++ - C++中聚集在一起的运算符如何分开

javascript - 如何为字符串生成唯一但一致的 N 位哈希(小于 64 位)?

c++ - 为什么我的函数调用不匹配这个通用函数实现?