static constant value vs static constant function

Dear all,

I would like to ask if anyone knows the difference between:

1. declaring a static constant value inside a class
2. declaring a static function that returns the same constant

More specifically, looking at the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<cstdio>

class My1
{
	public:
	My1() {}
	static const int number = 4;
	inline static const int integer() {return 4;}
};


int main()
{
	const int constant_value  = My1::number;
	const int constant_return = My1::integer();
	printf("static constant        -> %d\n", constant_value);
	printf("static member function -> %d\n", constant_return);
}


is there any reason to prefer one of the two following possibilites?
 
static const int number = 4;

or
 
inline static const int integer() {return 4;}




thank you all for your kind help,
Panecasareccio.
Look at std::numeric_limits: it has both static member constants (is_signed, digits, radix, max_exponent) and static member functions (max(), epsilon(), infinit()).

The defining choice in its pre-C++11 design was whether the constant is always an integer (which means it is possible to initialize such static const member inside the class): numeric_limits<T>::radix is always an integer, numeric_limits<T>::max() can be a double.

Integer constants were more useful than functions because they can be used a constant expressions (as template parameters, array sizes, etc). With C++11, this distinction is less important, since functions can be constexpr too.
Last edited on
Topic archived. No new replies allowed.