Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private Class within Namespace

I have a class within a namespace in a header file. The class requires a template type, and I only want certain types to be used. Below shows an example.

File a.hpp

// a.hpp
namespace a_ns {
template<class T>    
class a {
    // stuff
};
typedef a<double> a_double;
} // end of namespace
// stuff

File b.hpp

// b.hpp
#include <a.hpp>
namespace b_ns {
    typedef a_ns::a_double b;
}

File main.cpp

// main.cpp
#include "b.hpp"
int main() {
    b_ns::b my_b; // <<<--- I LIKE this!
    a_ns::a<float> my_a_which_is_not_allowed; // <<<--- I DO NOT LIKE THIS THOUGH! D:
}

So as you can see from the rather longed out example, the end objective is to NOT ALLOW the end user to declare a class a with float as the typename, and to only be able to use the pre-defined classes with specific types, as declared by typedef a<double> a_double;.

I thought this example above would allow this, however I was wrong, as I can create an a<float> as above, because I include b.hpp, which in turn includes a.hpp! So you see the problem! (hopefully?)

There is probably a simple solution, if this is at all possible.

like image 788
FreelanceConsultant Avatar asked Aug 23 '13 17:08

FreelanceConsultant


People also ask

Can you declare a private class in a namespace?

Private. You can use Private only at module level. This means you can declare a private element inside a module, class, or structure, but not at the level of a source file or namespace, inside an interface, or in a procedure.

Can I define private class in C#?

You cannot have a private class unless it is nested.

Can we create instance of private class in C#?

Can you create object of class with private constructor in C#? No, object of a class having private constructor cannot be instantiated from outside of the class.


1 Answers

If you only want to be able to use the type aliases and not use a directly, you can put it into an implementation namespace that users should know not to use:

namespace a_ns {

namespace detail {
    template<class T>        
    class a {
        // stuff
    };
}

typedef detail::a<double> a_double;
} // end of namespace

Now anything can use a_double, but to use a directly, your detail namespace would have to be dug into, and that's generally accepted as a bad thing to do. If a user decides they want to do that, they've already given up on staying out of trouble and you shouldn't take extra measures to stop them from hurting themself.

like image 56
chris Avatar answered Oct 17 '22 06:10

chris