Using a namespace in place of a static class in C++?

前端 未结 4 1805
一整个雨季
一整个雨季 2020-12-29 03:29

Is it good or okay practice to use a namespace as a static class? For example:

namespace MyStaticFunctions {
    void doSomething();
}

Vers

4条回答
  •  一个人的身影
    2020-12-29 03:47

    In C++, you are actually encouraged at the language level to use a namespace rather than a class containing only static methods because of Koenig's lookup (aka Argument Dependent Lookup).

    Example:

    namespace geometry {
        struct Point { int x, y; };
    
        double distance_from_center(Point const& p) {
            return sqrt(p.x * p.x + p.y + p.y);
        }
    } // namespace geometry
    
    int main() {
        geometry::Point const p{3, 4}; // must qualify
    
        std::cout << distance_from_center(p) << "\n"; // not qualified
    }
    

    If distance_from_center is written as a static method in a class, then you need to explicitly qualify it each time.

提交回复
热议问题