Hide template helper functions - static elements or an unnamed namespace

I am trying to write a library where I have some template functions, some of which are helper functions, so I do not want my users to have access to them. Some basic code may be

//mylib.h namespace myfuncs { template<class T> void helper (T input, int extrainformation) { //do some usefull things } template<class T> void dostuff(T input) { int someinfo=4; helper(input, someinfo); } } 

Is it possible to somehow hide the helper function so that library users cannot call it directly? I thought an unnamed namespace could do the job, but since I use templates, I cannot separate the function declaration and body between the header and implementation file. Putting an unnamed namespace in the header file is useless and bad. The only thing I can do is create mylib class and encapsulate functions as private / public static functions.

Any better solutions would be greatly appreciated.

Phil

+6
source share
3 answers

One way to do this is to have a โ€œverboseโ€ or โ€œinternalโ€ namespace. Thats how many libraries it does.

 namespace myfuncs { namespace detail { template<class T> void helper (T input, int extrainformation) { //do some usefull things } } template<class T> void dostuff(T input) { int someinfo=4; detail::helper(input, someinfo); } } 
+8
source

Do what many template libraries do (e.g. Eigen): use an explicitly named namespace to implement (e.g. myfuncs::impl ) and rely on social encapsulation (i.e. the user does not want to call templates from the implementation namespace).

+3
source

You can:
In header.h:

 #ifndef AAA_H #define AAA_H namespace myfuncs { template<class T> std::string dostuff(); } #include "aaa.cpp" #endif // AAA_H 

In source.cpp:

 #define AAA_CPP #include <string> namespace { template<class T> std::string helper () { return "asdf"; } } namespace myfuncs { template<class T> std::string dostuff() { return helper<T>(); } } #endif // AAA_CPP 

In main.cpp:

 #include <iostream> #include "aaa.h" int main(int argc, char *argv[]) { std::cout << myfuncs::dostuff<std::string>(); return 0; } 
0
source

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


All Articles