Search code examples
c++templatesc++14anonymous-class

How to restrict template class to only specific specializations with type aliases


What I aim to achieve is to have a templated Wrapper class with various aliases. Here is a simplified preview:

template < typename Type >
class Wrapper {
public:
   Wrapper(Type* resource) : ptr(resource) {}
   ~Wrapper() { free(ptr); }

private:
   Type* ptr;
}

void free(SDL_Window* ptr) { SDL_DestroyWindow(ptr); }
void free(SDL_Renderer* ptr) { SDL_DestroyRenderer(ptr); }

using Window = Wrapper<SDL_Window>;
using Renderer = Wrapper<SDL_Renderer>;

I would like to allow creation of only these aliased instances of Wrapper class. One of the reasons, is that this being wrapper to a SDL resource pointers, it has different memory freeing functions depending on type of the pointer.

Best scenario I would like to achieve would be to make Wrapper class not visible outside the usage of aliases I create. Maybe there is a solution using anonymous namespace, but thaw would mean wrapper class can't be in header file.


Solution

  • Best scenario I would like to achieve would be to make Wrapper class not visible outside the usage of aliases I create.

    This is possible using private and a wrapper class

    class WrapperAccessor {
        template < typename Type >
        class Wrapper {
        public:
           Wrapper(Type* resource) : ptr(resource) {}
           ~Wrapper() { free(ptr); }
    
        private:
           Type* ptr;
        };
    
    public:
        using Window = Wrapper<SDL_Window>;
        using Renderer = Wrapper<SDL_Renderer>;
    };
    
    using Window = WrapperAccessor::Window;
    using Renderer = WrapperAccessor::Renderer;