Advantages of classes with only static methods in C++

前端 未结 8 1668
谎友^
谎友^ 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:24

    As many others have pointed out, free functions inside a namespace is an approach that's often taken for this sort of thing in c++.

    One case I'd make for classes with all static functions is when you'd like to expose a set of functions to information derived from template parameters, i.e.

    template <typename Ty>
        class utils
    {
    public :
    // if you need to setup a bunch of secondary types, based on "Ty" that will be used 
    // by your utility functions
        struct item_type
        { 
            Ty data;
            // etc
        }; 
    
    // a set of utilities
        static void foo(Ty &data1, item_type &item)
        { 
            // etc
        }
    };
    

    You can use this to achieve the effect of a template'd namespace:

    int main ()
    {
        double data;
        utils<double>::item_type item ;
        utils<double>::foo(data, item);
    
        return 0;
    }
    

    If you're not using templates just stick with namespaces.

    Hope this helps.

    0 讨论(0)
  • 2020-12-01 08:26

    In C++, just make them free functions. There's no need or reason to place them in a class at all. Unless you're doing shizzle with templates.

    0 讨论(0)
提交回复
热议问题