功能模板专业化的重要性和必要性 [英] Function template specialization importance and necessity
问题描述
我读了C ++ Primer,它说功能模板专业化是一个高级主题,但我完全失去了。
I read C++ Primer, and it says function template specialization is an advanced topic, but I am totally lost. Can anybody offer an example why function template specialization is important and necessary?
为什么函数模板不支持部分专门化而类模板呢?底层的逻辑是什么?
Why don't function templates support partial specialization while class templates do? What's the underlying logic?
推荐答案
基本上你的想法是你可以写一个通用的模板,但仍然可以处理特殊情况。使用特殊化的一个示例是 std :: vector
。 std :: vector< bool>
是一个特殊化,它包装 bool
元素,使得它们只使用一个元素,不是一个字节。 std :: vector< T>
工作方式类似于所有其他类型的正常动态数组。
Basically the idea is that you can write templates that behave in a generic way for the general case, but can still handle special cases. One example of where specialization is used is in std::vector
. std::vector<bool>
is a specialization that packs the bool
elements such that they only use one bit per element, not one byte. std::vector<T>
works like a normal dynamic array for all other types.
专业化是元编程。例如,下面是一个例子(来自维基百科)如何使用模板专用化在编译时计算阶乘。
The more advanced use for specialization is metaprogramming. For example, here's an example (from Wikipedia) of how to use template specialization to compute factorials at compile time.
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
这篇关于功能模板专业化的重要性和必要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!