views:

80

answers:

1

I am working on a template class Array, which accepts another template TRAITS as a parameter.

template <typename BASE, typename STRUCT>
    class Traits {
    public:
        typedef BASE   BaseType;
        typedef STRUCT Struct;
        // .. More here
     };

template <class TRAITS>
    class Array {
    public:
        typedef TRAITS                          Traits;
        typedef typename Traits::BaseType       BaseType;
        typedef typename Traits::Struct         Struct;

        Struct& operator[](size_t i)
        {
            // access proper member
        }
        // More here...
    };

I wanted to specialise the operator[] of Array based on the Traits::Struct, however I am stuck with the syntax. I am not sure whether it is possible at all.

template <typename B>
    typename Array<Traits<B, RuntimeDefined>>::Struct&
    Array<Traits<B, RuntimeDefined>>::operator[](size_t a_index)
    {
        // Access proper member differently
    }

Compiler (g++ 4.4) complains:

In file included from array.cpp:8:
array.h:346: error: invalid use of incomplete type ‘class Array<Traits<N, RuntimeDefined> >’
array.h:26: error: declaration of ‘class Array<Traits<N, isig::RuntimeDefined> >’

EDIT.

The solution is based on the proposal by aaa and it looks like this:

        Struct& operator[](size_t i)
        {
            return OperatorAt(i, m_traits);
        }

        template <typename B, typename S>
            inline Struct& OperatorAt(size_t i, const Traits<B, S>&)
            {
                // return element at i
            }

        template <typename B>
            inline Struct& OperatorAt(size_t i, const Traits<B, RuntimeDefined>&)
            {
                // partial specialisation
                // return element at in a different way
            }
A: 

if I know correctly, you had to specialize entire class. instead of doing that, I create specialized functions parameterized for particular class:

For example:

    Struct& operator[](size_t i)
    {
        return operator_(i, boost::type<TRAITS>());
    }
private:
    template<class B>
    Struct& operator_(size_t i, boost::type<B>); // generic
    Struct& operator_(size_t i, boost::type<A>); // specialized

if you need more fine-grained control, you can use free functions, boost::enable_if, boost::mpl etc.

aaa
Thank you very much for providing a different point of view on the solution.
matejk