简体   繁体   中英

c++ source code organization for free functions

I want to start to prefer free (non-member) functions over member functions - following this article http://www.drdobbs.com/184401197

I am used to organize my C++ classes in that way, that I have ClassName.h for the declaration and a ClassName.C for the implementation.

ClassName.h :

struct ClassName { 
    ClassName();
    void setData( unsigned data );
};

and the implementation is then

ClassName.C :

#include "ClassName.h"

ClassName::ClassName() { dosomething(); };
void setData( unsigned data ) { dootherthings(); }; 

So how do I organize my code when I want have a free function adjustClassData() ? I also want to put this function into namespace.

Assuming ClassName is in namespace foo , then I would put the free function into namespace foo as well:

namespace foo {
    void adjustClassData( ClassName & inObj );
}

I am looking for the aspects of namespace and suggestions for file names.

I am looking for some best-practices - as there is no C++ rule in the standard prescribing the file organization.

You could put the free functions that deal with a particular class in the class header and implementation file if there are not too many.

Otherwise, come up with a naming convention and put them in a separate header and implementation file (eg ClassNameFunctions.h/.cpp).

If you're looking to replace member functions with free functions, I'm assuming these free functions are tightly related to the class in question. In which case, they shouldn't be public. I'd go with anonymous inner namespaces:

//myclass.h
namespace myNamespace
{
   class MyClass
   { 
      void foo();
   };
}

//myclass.cpp
#include "myclass.h"
namespace myNamespace
{
   namespace
   {
      void helper() {};
   }
   void MyClass::foo()
   {
   }
}

i suggest to put the declaration of the free functions in a seperate header, as they are not part of the class itself, however i would put all in the same namespace.

//Bar.h
namespace foo{
class Bar{}
}

In the header where declaring the free functions i would use forward declaration for the class itself.

//BarHelper.hpp
namespace foo{
class Bar;
void somefunc(&Bar);
}

Implementation as usual in seperate files.

Right now i am crawling through tons of header files where declaration and definition of often several classes and free functions are mixed. It is a real pain.

So KISS ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM