开发者

C++ static-only class

开发者 https://www.devze.com 2023-04-10 04:15 出处:网络
I have a bunch of functions that I want to put in either a separate namespace or a class. Out of the two, which would be better? If it\'s the latter, how should I go about it? I mean, I don\'t have an

I have a bunch of functions that I want to put in either a separate namespace or a class. Out of the two, which would be better? If it's the latter, how should I go about it? I mean, I don't have any instance members, so should I specify the constructor as private? Or delete it?

Eith开发者_如何学Goer way, it will look something like this to give you an idea:

myproject::foo::f()


C++ namespaces and class can both contain functions and other types, but there are some key differences in behavior. You'll have to decide which is best for your particular circumstance.

  • Classes can be templated, namespaces can't. This provides a way to pass a set of template arguments to a whole group of functions and other types. Combined with typedef, this can be very powerful.

  • You can use using namespace xyz; to bring a whole group of namespace members into any scope. Classes can be inherited to bring them into scope (has not much effect if there are no instance members, due to the empty base optimization, but static members can then be used without qualification), but this only works inside other classes. Free functions would have to explicitly qualify all access to members of the class.

  • Namespaces participate in argument-dependent lookup, members of a parent class don't.

If you want to use the trick of inheriting a class to supply template arguments and gain unqualified access to its static members, then you should leave the constructor and destructor as defaulted and trivial, instead of deleting or making them inaccessible. In C++11, you can mark the constructor both protected and defaulted.


If you use the class it is best to declare the default constructor, copy constructor, assignment operator, and destructor private / unimplemented (plus maybe some more for C++11). If you don't you'll have a class that can be used to make useless objects. If you use a namespace you don't have to do any of that.

Classes are made for objects. Using them as containers of static functions, no member data, is more abuse than use.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号