Advantages of classes with only static methods in C++

前端 未结 8 1676
谎友^
谎友^ 2020-12-01 07:28

Even though there are no static classes in C++, coming from a Java background I use to create a helper class like Util containing only static methods. Is this c

8条回答
  •  再見小時候
    2020-12-01 08:21

    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 
    
    template
    struct Fibonacci 
    {
       static const int value = Fibonacci::value + Fibonacci::value;
       static void print()
       {
           Fibonacci::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

提交回复
热议问题