C++ Classes – Handling Classes Used Only Once

c

I have a class that basically builds up a memory-efficient version of a structure to be used in a performance-critical section of code.

The resulting structure is ugly but extremely fast, so not using it isn't really an option, but I also can't use it as the only representation of my structure because it has parts not relevant to the analysis stripped. Did I mention it's also very ugly?

Let's call this class Fast. I also have the original, pretty representation, let's call it Pretty. I have a function called Process() which is supposed to take in an instance of Pretty, convert it to Fast and then do a few million calculations on it and spit out a result:

Pretty pretty;
// do stuff with pretty

// in another hpp:
double Process(const Pretty& pretty)
{
  Fast fast(pretty); // create my fast object

  // do some processing on fast

  return result; // at this point fast dies
}

The instance of Fast is created and dies within Process, but unfortunately I can't declare a class within a function, so I have to declare it elsewhere.

What I would like to do is make the entire class accessible only to Process, and not even have it seen by anyone else (just like I would conversely declare a function private if the class were the only object that should have access to it). But I can't declare a class private!

Here's my current attempt:

class Process
{
public:
  static double DoProcess(Pretty pretty); // this is the process function

private:
  class Fast
  {
    // construct fast here (only Process can see this class!)
  };
};

And then I just call Process::DoProcess(). This isn't really a critical issue so I didn't post it on SO, but it's a style question and I would really like to have a neat solution! I've never come across this issue before and was wondering how others have dealt with it, and if they came up with a nicer solution.

Best Answer

I can see three viable options here, where from a design perspective I find the bottom one most attractive.

One is to indeed use your approach, perhaps with operator() to avoid redundancy.

Another option is to define the class inside the function itself (this is allowed now).

However, chances are you may need the class later, and honestly I doubt that your namespace is so littered that you can't offer the Fast class file scope.

In this scenario, declare the Process method in your header and define it in a .cpp file, underneath the definition of your Fast class, which you should wrap in an anonymous namespace.

Either way, I would pull out the definition from the header. Faster compilation is a nice gain, but the biggest perk is keeping interface and implementation separate.