Advantages of classes with only static methods in C++
In C++, classes with only static
methods is mostly used in template metaprogramming.
For example, I want to calculate fibonacci numbers at compile-time itself, and at runtime I want them to print only, then I can write this program:
#include <iostream>
template<int N>
struct Fibonacci
{
static const int value = Fibonacci<N-1>::value + Fibonacci<N-2>::value;
static void print()
{
Fibonacci<N-1>::print();
std::cout << value << std::endl;
}
};
template<>
struct Fibonacci<0>
{
static const int value = 0;
static void print()
{
std::cout << value << std::endl;
}
};
template<>
struct Fibonacci<1>
{
static const int value = 1;
static void print()
{
Fibonacci<0>::print();
std::cout << value << std::endl;
}
};
int main() {
Fibonacci<20>::print(); //print first 20 finonacci numbers
return 0;
}
Online demo : http://www.ideone.com/oH79u
If you want to create a collection of utility functions without clobbering the global namespace, you should just create regular functions in their own namespace:
namespace utility {
int helper1();
void helper2();
};
You probably don't want to make them static functions either. Within the context of a non-member function (as opposed to a member function), the static keyword in C and C++ simply limits the scope of the function to the current source file (that is, it sort of makes the function private to the current file). It's usually only used to implement internal helper functions used by library code written in C, so that the resulting helper functions don't have symbols that are exposed to other programs. This is important for preventing clashes between names, since C doesn't have namespaces.