C++的template 模版类(仅函数)

版权声明:Copyright © 2019年 Lcost. All rights reserved. https://blog.csdn.net/m0_43448982/article/details/88053124

打acm的时候遇到过大量的数据,所以备有一些快读的模版。但是那么多的数据类型,就会出现下面这种情况:

inline bool FastRead (int& x) {
    x = 0; char f = 0; int ch = getchar();
    if (ch == EOF) return false;
    while(ch > '9' || ch < '0') { f |= (ch == '-'); ch = getchar(); }
    while(ch <= '9' && ch >= '0') { x = x * 10 + ch - 48; ch = getchar(); }
    if (f) x = -x;
    return true;
}
inline bool FastRead (long long& x) {
    x = 0; char f = 0; int ch = getchar();
    if (ch == EOF) return false;
    while(ch > '9' || ch < '0') { f |= (ch == '-'); ch = getchar(); }
    while(ch <= '9' && ch >= '0') { x = x * 10 + ch - 48; ch = getchar(); }
    if (f) x = -x;
    return true;
}
inline bool FastRead (double& x) {
    x = 0; char f = 0; int ch = getchar(); double d = 0.1;
    if (ch == EOF) return false;
    while(ch > '9' || ch < '0') { f |= (ch == '-'); ch = getchar(); }
    while(ch <= '9' && ch >= '0') { x = x * 10 + ch - 48; ch = getchar(); }
    if (ch == '.') {
        ch = getchar();
        while(ch <= '9' && ch >= '0') { x += d * (ch - 48); d *= 0.1; ch = getchar(); }
    }
    if (f) x = -x;
    return true;
}

为了支持各种不同的类型,硬是为每一种类型准备了一个快读,以至于出现了几百行的快读……

后来了解到一个C++关键词:template
果断把这么多行代码改成了这样:

template <class __T>
inline bool FastRead (__T& x) {
    x = 0; char f = 0; int ch = getchar(); double d = 0.1;
    if (ch == EOF) return false;
    while(ch > '9' || ch < '0') { f |= (ch == '-'); ch = getchar(); }
    while(ch <= '9' && ch >= '0') { x = x * 10 + ch - 48; ch = getchar(); }
    if (ch == '.') {
        ch = getchar();
        while(ch <= '9' && ch >= '0') { x += d * (ch - 48); d *= 0.1; ch = getchar(); }
    }
    if (f) x = -x;
    return true;
}

Xcode编译器自动补全提供的格式如下

template <<#template parameters#>>
<#return type#> <#function name#>(<#function parameters#>) {
    <#statements#>
}

大致格式解释:

<#template parameters#> 模版参数
<#return type#> 返回类型
<#function name#> 函数名
<#function parameters#> 函数参数
<#statements#> 函数体

上面的快读例子稍微有些难以看懂,这里补充一个很简单的例子:两个数相加

template <class T>
T add(T a, T b)
{
    return a + b;
}

使用模版类的时候可以给模版类参数指定默认值,并且可以正常使用

template <class T>
T add(T a, T b = 1)
{
    return a + b;
}
int main()
{
	cout<<add(1);
}

甚至,模版类可以当作一个函数去使用(示例:sort)
但是,模版类不能默认为一个函数,例如:

template <class T>
bool comp(int a, int b, T f = less<int>() )
{
    return f(a,b);
}
int main()
{
	cout<<comp(1, 2)<<endl;//error:No matching function for call to 'comp'
	cout<<comp(1, 2, less<int>() )<<endl;//success
}

细心的人也许想到STL中的一个函数:sort
当只提供两个参数时,sort的第三个参数默认为 less<类型>(),而且sort也是一个模版类函数。

而真实的情况如下:

template <class RandomIt, class Compare>
void sort(const RandomIt first, const RandomIt last, Compare comp)
{
	<#statements#>
}
template <class RandomIt>
void sort(const RandomIt first, const RandomIt last)
{
	sort(first, last, less<*RandomIt>() );
}

猜你喜欢

转载自blog.csdn.net/m0_43448982/article/details/88053124