Domanda

Im currently studying c++ templates and there's something I don't understand. So far I understand if you have the following generic class

    template <class T> class A{
        ...
    }

To provide a specific specialization of the class, say for int objects, you'd define the following:

    template<> class A<int>{
        ...
    }

However, I have been seeing cases similar to the following:

Original class is,

    template <class T, int Size> class buffer{
        ...
    }

Then the speciliazed class for objects of type int is,

    template <int Size> class buffer<int, Size>{
        ...
    }

I'm confused as why the specilization for int is not the following:

    template<> class bufffer<int, int Size>{
        ...
    }

Can someone please explain.

È stato utile?

Soluzione

This buffer template has two template parameters. The first is a type parameter because it begins with class, and the second is a non-type parameter because it begins with int.

What you are seeing is a partial specialization on only the first parameter. Note that the template arguments for a template specialization are totally independent of the template arguments for the original template (this is one of the major things that confused me when I was learning this). For example, it would work just as well as:

template <int N> class buffer<int, N> { ... };

It is basically giving a specialization for when the first template argument of buffer is the type int and the second is some int value.

Whenever you start with template <> (empty brackets), that is an explicit specialization where you are specifying all of the template arguments. For example, you could do:

template <> class buffer<int, 1> { ... };

This would be a specialization for when the first template argument is the int type and the second is the value 1.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top