Private class in namespace

I have a class in the namespace in the header file. The class requires a template type, and I want certain types to be used. The following is an example.

A.hpp file

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

B.hpp file

 // 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 a rather elaborate example, the ultimate goal is to NOT ALLOW the end user to declare class a with float as the type name and only be able to use predefined classes with specific types declared typedef a<double> a_double; .

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

Perhaps this is a simple solution, if at all possible.

+6
source share
2 answers

If you only want to use type aliases and not use a directly, you can put it in 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 something can use a_double , but to use a directly, your detail namespace must be dug up, and this is considered bad. If the user decides that they want to do this, they have already abandoned the trouble, and you should not take additional measures to prevent them from harming themselves.

+7
source

Here you can use static_assert

 #include <type_traits> template <typename T> class X { T i; static_assert(!std::is_same<float,T>::value,"Don't use floating point"); }; int main() { X<int> a; //X<float> b; fails at compile time return 0; } 

This will work until the variable is const or volatile

0
source

Source: https://habr.com/ru/post/952385/


All Articles