Where should I put user-defined concepts in my C++ project file structure?

Viewed 181

I am writing a templated function func that takes as input a matrix. I provide a SquareMatrix class that is compatible with func, but I want other matrix implementations to be compatible with func. For that reason, I have defined a concept for matrix.

template<typename T>
concept Matrix = requires (T a, int b, int c) { 
    {a(b, c)} -> std::convertible_to<double>;
    {a.size1()}->std::convertible_to<size_t>;
    {a.size2()}->std::convertible_to<size_t>;
};

I use this concept in 3 places. In my SquareMatrix.h and my SquareMatrix.cpp, I use it to define a templated constructor that produces a SquareMatrix from another Matrix. In func.h, I use it to define the templated function func. func.h imports SquareMatrix.h.

I now need to decide in what file I should put my user-defined concept Matrix. I have several questions related to this decision:

  1. In what file should I put my Matrix concept? What should be the file name and extension?
  2. Should each concept be in its own file? Should all the concepts for my project share a file?
  3. I am using the Visual Studio IDE. Does that change anything?
1 Answers

Based on my experience, these are my recommendations:

  1. This is a concept about matrices, so it is reasonable to write it in 'SquareMatrix.h', either at the top of the file with other concepts or just before the definition of class 'SquareMatrix'. In general, you want your concepts to be defined where a reviewer would find easier to look for it.
  2. I don't think it is a good idea to separate all concepts into an independent file. Rather, all functions, classes and concepts related to an API should be close together. In this case, the API is related to square matrices, so all those entities should share the same file. That way you avoid jumping from file to file when reviewing, extending or fixing code.
  3. Standard C++ is the same whether you use it on VS or anywhere else. If you are developing open source code, your collaborators will access the code in any IDE, or even with just text editors (i.e. vim, emacs). C++ is the same language for all of them.

One more thought: There are excellent matrix libraries out there. Check, for example, Armadillo, Eigen or Blaze. Instead of developing your own matrix library, it is more convenient and the code will be more efficient if you use a library.

Related