Creating a container 'thing' in C++ to hold static functions. What should 'thing' be?
I'm currently building a set of common functions (Search algorithm implementations), and think I'm doing the grouping wrong. At the moment, I have a class, Sorting, that is declared in a file called Sorting.h (it's nowhere near finished yet, btw) like so:
#ifndef SORTING_H
#define SORTING_H
#include <vector>
class Sorting {
private:
Sorting();
Sorting(const Sorting& orig);
virtual ~Sorting();
public:
static void bubbleSort(std::vector<int>& A);
// etc
};
#endif /* SORTING_H */
Now, because the constructor is private, a user cannot instantiate my class - it effectively is just a holder for static functions that the user can call. However, from what I have read of C++ so far - and from looking at the STL libraries etc- I think I'm doing this wrong. Should I instead have a namespace called 'Sorting' or something of the 开发者_如何转开发sort? If so, what does my header file (the one the user would include) look like? And would I have to change the structure of the rest of the files? At the moment each set of algorithms is in it's own cpp file (i.e. BubbleSort.cpp, CocktailSort.cpp, etc).
Apologies for what may be a duplicate question - I did search for C++ and namespace, but I got very general questions about namespaces back and none seemed to be this specific problem.
Use a namespace. The callers of the code won't need to care. Also, you need to template on any sortable type- a sort that can only sort a vector of integers is rather bad. Stick to the definition provided by std::sort.
namespace Sorting {
template<typename Iterator> void cocktail_sort(Iterator a, Iterator b) {
// implement cocktail sort
}
template<typename Iterator> void bubble_sort(Iterator a, Iterator b) {
// implement bubble sort
}
};
The caller won't care whether you're statically in a class, but the simple fact is that you waste semantics and time having it in a class, and it doesn't accurately represent the intention. It's not wrong, per se, but it is kinda bad. Using a namespace also allows callers to use the using namespace Sorting; semantics.
It doesn't matter, a free function in a namespace achieves the same. The syntax for calling it is identical.
I'll recomend using a namespace if the class is not to be instantiated.
精彩评论