Lucas Myers
Lucas Myers

Reputation: 404

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. Also suppose that I always want num to be some particular value (say 5) for baz as defined in Foo. 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;, but that would create an extra integer for every instance of Foo, which is not ideal if I have lots of instances. I have also considered defining a constant variable outside the class definition but in the header file. This has the advantage of being seen in the .cpp file, but pollutes the global name space.

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.

Upvotes: 0

Views: 462

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63839

You want a single static variable, common to all instances of 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.

Upvotes: 2

Related Questions