How to hide an implementation helper template?

后端 未结 5 2261
故里飘歌
故里飘歌 2020-12-15 05:21

Suppose that I have two template functions declared in a header file:

template  void func1(const T& value);
template          


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-15 06:00

    I would (as said before) make a template class, make all functions static and the helper function private. But besides that I'd also recommend making the constructor private as shown below:

    template 
    class Foo{
    public:
      static void func1(const T& value);
      static void func2(const T& value);
    private:
      Foo();
      static void helper(const T& value);
    }
    

    When you make the constructor private, the compiler won't allow instances of this template class. So the code below would become illegal:

    #include "foo.h"
    
    int main(){
      int number = 0;
      Foo::func1(number); //allowed
      Foo::func2(number); //allowed
      Foo::helper(number); //not allowed, because it's private
      Foo foo_instance; //not allowed, because it's private
    }
    

    So why would someone want this? Because having different instances that are EXACTLY the same is something you probably never want. When the compiler tells you that the constructor of some class is private, then you can assume that having different instances of it would be unnecesarry.

提交回复
热议问题