注册 登录
编程论坛 C++教室

这个程序怎么改呀?

songhuirong1 发布于 2010-12-27 20:34, 559 次点击
#include <iostream>
using namespace std;

template <typename Type,int size>
void count(Type (&r_array)[size], Type value)
{
    int cnt = 0;

    for(int ix=0;ix<size;++ix)
    {
        if(value == r_array[ix])
            ++cnt;
    }

    cout << value << "出现次数为" << cnt << endl;
}

template <> void count<char>(char (&ch_array)[size], char ch)
{
    int cnt = 0;

    for(int ix=0;ix<size;++ix)
    {
        if(ch == ch_array[ix])
            ++cnt;
    }

    cout << ch << "出现的次数为" << cnt << endl;
}

int main()
{
    int a[] = {34,56,12,31,12,34,12,34,12};
    double b[] = {24.0,34.3,24.0,12.3,34.1,24.0};
    char ch[] = "hello songhuirong.";

    count(a,12);
    count(b,24.0);
    count(ch,'o');
   
    return 0;
}
这是一个模板特化实例的程序,但是编译报错,改怎么改呢?说size是未声明的标识符。
6 回复
#2
aufish2010-12-27 21:40
#include <iostream>
#include <string.h>
using namespace std;

template <typename Type>
void count(Type *r_array, Type value,int size)
{
    int cnt = 0;

    for(int ix=0;ix<size;++ix)
    {
        if(value == r_array[ix])
            ++cnt;
    }

    cout << value << "出现次数为" << cnt << endl;
}


int main()
{
    int a[] = {34,56,12,31,12,34,12,34,12};
    double b[] = {24.0,34.3,24.0,12.3,34.1,24.0};
    char ch[] = "hello songhuirong.";

    count(a,12,9);
    count(b,24.0,6);
    count(ch,'o',strlen(ch));
   
    return 0;
}
#3
songhuirong12010-12-28 09:11
2楼的,我是要用模板显式特化来处理字符数组,其它的就用通用模板定义来实现,你搞错我的意思了。
#4
lintaoyn2010-12-28 09:59
程序代码:
template<int size> void count(char (&ch_array)[size], char ch)
{
    int cnt = 0;

    for(int ix=0;ix<size;++ix)
    {
        if(ch == ch_array[ix])
            ++cnt;
    }

    cout << ch << "出现的次数为" << cnt << endl;
}
部分特化应该是不行的。改用重载。
#5
songhuirong12010-12-28 11:52
回复 4楼 lintaoyn
高手啊。解决了。我再问下,像形如template <typename T,int size>的函数模板可以进行显式特化吗?就是说模板参数表中包含了其它非模板参数,比如这里的int size。
#6
lintaoyn2010-12-28 13:58
可以
const int cint = 10;
template<> void count<char,cint>(char (&ch_array)[cint], char ch);
或者
template<> void count<char,10>(char (&ch_array)[10], char ch);
template<> void count(char (&ch_array)[10], char ch);
不过你连非类型模板参数都特化了,也就没必要写成模板,直接写成同名的普通函数。
#7
songhuirong12010-12-28 16:51
回复 5楼 songhuirong1
非常感谢你。以后多多指教。
1