Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for specialization of nested template class

I'm trying to figure out the correct syntax for explicit specialization of a nested template class. The following code will better illustrate:

struct Column_Major;
struct Row_Major;

template<size_t rows, size_t cols, typename T, typename Allocator>
class Matrix
{

    /* bunch of members */
    template <typename storage = Column_Major>
    class Iterator
    {
        /* bunch of members */
    };
};

I'd like to write an explicit specialization for template <> class Matrix<...>::Iterator<Row_Major, but the syntax is eluding me. I have a suspicion that it is not possible to explicitly specialize the Iterator class without an explicit specialization of the containing class, Matrix. But I would be very happy if there is a way to do this.

I know I could make the Iterator class a separate class, not a member of the Matrix class, but having the classes nested as such allows me full access to the template parameters and datamebers of the Matrix class, which simplifies things. I know I could work around this if I need to, but I'd first like to investigate and understand the possibilities for the nested approach.

Thanks, Shmuel

like image 374
Shmuel Levine Avatar asked Oct 29 '13 16:10

Shmuel Levine


People also ask

What is the syntax of template class?

1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.

What is the syntax for explicit class specialization?

What is the syntax to use explicit class specialization? Explanation: The class specialization is creation of explicit specialization of a generic class. We have to use template<> constructor for this to work. It works in the same way as with explicit function specialization.

What is a template specialization in C++?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.


1 Answers

For explicit specialization, you need to specialize the outer class before the inner, you can see this question for example.

There is a workaround that is using partial specialization:

template<size_t rows, size_t cols, typename T, typename Allocator>
class Matrix
{

    //                           Notice the additionnal dummy parameter
    //                                       vvvvvvvvvvvvv
    template <typename storage = Column_Major, bool = true>
    class Iterator
    {
    };

    // Specialization
    template <bool dummy>
    class Iterator<Row_Major, dummy>
    {
    };
};
like image 87
Synxis Avatar answered Sep 29 '22 01:09

Synxis