Namespace + functions versus static methods on a c

2019-01-01 13:59发布

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:

  1. Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
  2. Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()

Why would I choose one over the other as a means of organizing my software?

7条回答
谁念西风独自凉
2楼-- · 2019-01-01 14:52
  • If you need static data, use static methods.
  • If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.

Otherwise, use namespaced functions.


In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:

template<typename T, int decimalPlaces>
class MyMath
{
   // routines operate on datatype T, preserving at least decimalPlaces precision
};

// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;

If you don't need that, then by all means use a namespace.

查看更多
登录 后发表回答