C++ Scope – Nested Classes vs Namespaces

cnamespacescope

Is it good to use nested classes or should I use namespaces instead?

In context:

I have a templated codec loader and a codec have In objects and Out objects

template<class TypeOfData>
class Codec
    {
    private:
        typename TypeOfData::In* reader;
        typename TypeOfData::Out* writer;
    };

On the other hand, I cannot use

using TypeOfData;

if i dont want to :: my way to a static method.

Best Answer

Personally, I like this approach, because:

  • It is a way to standardize class type definitions. If you want you can see it as a kind of interface definition for types to be used for template instantiation, because you cannot instantiate this template with arbitrary types (for 'TypeOfData' type variable). Instead, a concrete 'TypeOfData' must define an inner 'In' and an 'Out' type definition.
  • You avoid writing a template which needs three type variables (in this concrete case) -- something like

    template <class TypeOfData, class TypeOfIn, class TypeOfOut>
    class Codec
    {
    private:
        TypeOfIn* reader;
        TypeOfOut* writer;
    };
    

    which makes instantiating this template more complex. Also, you can pass any types for 'TypeOfIn' and 'TypeOfOut'. While this is more generic, it might not be the intention of the template's author. In this concrete case you can see, that there must be exactly one 'In' and one 'Out' type associated with a class 'TypeOfData', which is defined by 'TypeOfData' itself. Using a template with three type variables wouldn't tell you anything about these constraints. Furthermore, the template instantiator (client code) would have to know what 'TypeOfIn' and 'TypeOfOut' he had to use with a class 'TypeOfData'. And this will cause problems if, sometime in the future, the associated 'TypeOfIn' and 'TypeOfOut' types to be used with 'TypeOfData' change. Using the OP's version, client code would likely not have to change, because the template gets the correct types to use from 'TypeOfData' and not by client code.

So I think using this approach is good if these arguments match your requirements. BTW, in that case I wouldn't mind being forced "to :: my way to static method" (or type definitions). If they don't, however, you might be better off using another approach and profit from a possibly more generic (template) solution.

Related Topic