简体   繁体   English

在哪里定义用于 C++ 中 class 的模板成员变量的常量?

[英]Where to define constants for use in a template member variable of a class in C++?

Suppose I want to define a class Foo which has a member variable that is also a template Bar<int num> baz .假设我想定义一个 class Foo ,它的成员变量也是模板Bar<int num> baz Also suppose that I always want num to be some particular value (say 5) for baz as defined in Foo .还假设我总是希望num成为Foo中定义的baz的某个特定值(比如 5)。 Then presumably I could accomplish this as follows:然后大概我可以按如下方式完成此操作:

class Foo
{
private:
    Bar<5> baz;
};

However, this would be introducing a magic number which is typically not good programming practice.但是,这将引入一个幻数,这通常不是好的编程习惯。 I have considered defining a constant in the class definition a la const int num = 5;我已经考虑在 class 定义中定义一个常量 a la const int num = 5; , but that would create an extra integer for every instance of Foo , which is not ideal if I have lots of instances. ,但这会为Foo的每个实例创建一个额外的 integer ,如果我有很多实例,这并不理想。 I have also considered defining a constant variable outside the class definition but in the header file.我还考虑在 class 定义之外但在 header 文件中定义一个常量变量。 This has the advantage of being seen in the .cpp file, but pollutes the global name space.这样做的好处是可以在.cpp文件中看到,但会污染全局名称空间。

My question is, what is the most stylistically appropriate way to accomplish this goal?我的问题是,实现这一目标的最适合风格的方式是什么? Ideally there would be some variable which is only visible to the header and .cpp file, and which can be used in the template call.理想情况下,会有一些变量只对 header 和.cpp文件可见,并且可以在模板调用中使用。

You want a single static variable, common to all instances of Foo .您需要一个static变量,该变量对Foo的所有实例都是通用的。

class Foo
{
private:
    static constexpr int num = 5;
    Bar<num> baz;
};

For the same reason magic numbers are considered bad , you also probably want a variable name more informative than num .出于同样的原因,幻数被认为是不好的,您可能还想要一个比num提供更多信息的变量名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM