Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 529
Stephen Avatar asked Aug 19 '10 20:08

Stephen


2 Answers

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.

like image 142
Puppy Avatar answered Oct 19 '22 20:10

Puppy


It doesn't matter, a free function in a namespace achieves the same. The syntax for calling it is identical.

like image 34
Hans Passant Avatar answered Oct 19 '22 22:10

Hans Passant