Search code examples
c++functiontemplatesprivatepublic

Can I define a private template function outside of a class?


I have two template functions, generatePerms and permute in a header file (not for a class, just a general header file with utility-type functions). I want generatePerms to be publicly accessible, but permute should not be. Is there any way to do this? I don't think I can use public: and private outside of a class, but maybe there's a way to structure the header file that can achieve this end?

Example header file:

//header.hpp
#ifndef H_UTILITY
#define H_UTILITY

#include <vector>

//this one should be private
template <typename T>
void permute( std::vector<T> values, int n, std::vector<T> *perms ){ /* do stuff */ }

//this one should be public
template <typename T>
std::vector<T> generatePerms( std::vector<T> values, int n ){ /* do stuff, calls permute() */ }

#endif

Solution

  • You can put the functions in a Util class as static functions like this

    //header.hpp
    #ifndef _H_UTIL_
    #define _H_UTIL_
    
    #include <vector>
    class Util
    {
        private:
        template <typename T>
        static void permute( std::vector<T> values, int n, std::vector<T> *perms ){ /* do stuff */ }
    
        public:
        template <typename T>
        static std::vector<T> generatePerms( std::vector<T> values, int n ){ /* do stuff, calls permute() */ }
    };
    #endif
    

    and use the public function with Util::generatePerms(...). (If you don't want to write Util::generatePerms(...) you can wrap it in a global function, though I would not recommend it.)