Alex Rivera | Logout

C++ Namespace Functions

Asked 2012-05-08T05:07:13.450
40

I am a Java developer and I am pretty new to C++. I need to implement some kind of utility class, and I was thinking of implementing the methods as static. However, I came across to this stackoverflow question about namespace functions vs static method, and apprently namespace functions is preferred approach. So I would like to konw if there is any article or example on how to implement namespace function. E.g, how should I declare namespace functions in header file? Should header only contain function definitions like class header file and implementations should be in cpp file, or should I straight away implement functions in header file?

Basically, I am trying to implement an application to parse a text file that contains some commands. So I am thinking of implementing static helper methods to handle text processing. E.g readCommand(string line). Please let me know if I am in the wrong direction. Thanks

Edit
Report

1 Answer

28

You can declare the functions in the header:

namespace A {
    void foo();
}

and implement in the .cpp:

namespace A {
  void foo() { std::cout << "foo!"; }
}

You can also put the implementation in the header, making sure to declare it inline to avoid breaking the one definition rule:

namespace A {
    inline void foo() { std::cout << "foo()!"; }
}

Note that putting the implementation in the header means that client code has a compilation dependency on the implementation, as well as on headers used for the implementation. In the example above, the client code now depends on the the header, and if we do something trivial like add an exclamation mark to the printout, we need to re-compile, as opposed to re-link, all the client code.

It is very important to put implementations of template functions in the header or in a file included by the header, these cannot go in the .cpp:

namespace B {
  template <class T>
  inline void foo(const T& t) { std::cout << t.name() << "\n"; }
}
answered 2012-05-08T05:24:53.830

Your Answer