0

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.

4

1 回答 1

0

buffer模板有两个模板参数。第一个是类型参数,因为它以 开头class,第二个是非类型参数,因为它以 开头int

您所看到的是仅对第一个参数的部分专业化。请注意,模板特化的模板参数完全独立于原始模板的模板参数(这是我在学习时感到困惑的主要事情之一)。例如,它的工作原理与以下内容一样好:

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

它基本上是针对第一个模板参数buffer是类型int而第二个是某个int值时的特化。

每当您以template <>(空括号)开头时,这是一个明确的特化,您可以在其中指定所有模板参数。例如,您可以这样做:

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

当第一个模板参数是inttype 而第二个是 value时,这将是一个特化1

于 2013-04-18T13:32:57.063 回答