Search code examples
c++c++11template-meta-programmingtype-traits

custom template programming


I am trying to write a container class that changes behavior depending on the based on a given dimension of the class as follow:

template <typename T, size_t DIM>
class Container { ... };

I tried to achieve that by using type_triats as follow:

template<typename T, size_t DIM, typename ENABLE = typename std::enable_if<
        std::integral_constant<bool, DIM == 1>::value>::type>
{ // implementation for 1D };

and for 2 d container as follow:

template<typename T, size_t DIM, typename ENABLE = typename std::enable_if<
            std::integral_constant<bool, DIM == 2>::value>::type>
    { // implementation for 2D };

by I get redefenition error ?!

Any idea how I can implement this customization.

Also, is there anyway that I can mask the implementaion of method using enable_if ??!!!


Solution

  • That's not what enable_if is for. What you most likely want is a straight-up specialization:

    template <typename, size_t> class Container;
    
    template <typename T> class Container<T, 1> {
      // 1-D impl
    };
    
    template <typename T> class Container<T, 2> {
      // 2-D impl
    };
    
    // etc.
    

    Common behaviour can be factored into base classes if needed.