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.
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.
You cannot have a private class unless it is nested.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With