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.
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.