模板类的对象如何作为函数形参

wgq2633 2008-11-11 10:57:33
bitset类就是上面所说的模板类
对于bitset<3>a,bitset<4>b,bitset<5>c,这些不同的bitset对象,希望函数CRC(a_)可以对a,b,c都能够调用,且能够把实参a/b/c这个对象定义时的模板形参传给函数(a对象的3,b对象4,c对象5可以传递给CRC函数)
我采用如下的定义:不行,求解

template<int Data_N_>
void CRC( bitset<Data_N_>& a_ )
{
int LEN = Data_N_;
}

希望CRC(a)时LEN=3,CRC(b)时LEN=4

谢谢。
...全文
138 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
wgq2633 2008-11-13
  • 打赏
  • 举报
回复
谢谢!!
在VC6.0上通过了
相当郁闷,前天晚上因为没有最终确定CRC()函数的格式,在文件的开头弄了个void CRC();在后面写刚楼顶上提到的函数,给了参数,调用的时候报“The CRC function doesn't take two parametres.”

今天一想,用模板实现好像很不合算吧?对不同的Data_N_都生成一份儿代码的话,代码就会无端变长了,还是改用别的方法吧
帅得不敢出门 2008-11-12
  • 打赏
  • 举报
回复
vc6.0过了.
gcc没过
可以这样改

#include <iostream>
#include <bitset>
using namespace std;

template<unsigned int Data_N_>
void CRC( const bitset<Data_N_>& a_ )
{
int LEN = Data_N_;

cout<<LEN<<endl;
}



int main()
{
CRC(bitset<5>());
CRC(bitset<3>());
CRC(bitset<1>());

return 0;
}
星羽 2008-11-12
  • 打赏
  • 举报
回复
g++ 的话确实编译不过,改成这样就好了


template<unsigned int Data_N_>
void CRC( bitset<Data_N_>& a_ )
{
int LEN = Data_N_;

cout<<LEN<<endl;
}



星羽 2008-11-12
  • 打赏
  • 举报
回复
上面是用vs2005 编译通过的,如果你编译不过,请说明你的编译器,和出错的说明
星羽 2008-11-12
  • 打赏
  • 举报
回复

#include "iostream"
#include "bitset"
using namespace std;

template<int Data_N_>
void CRC( bitset<Data_N_>& a_ )
{
int LEN = Data_N_;

cout<<LEN<<endl;
}

int main()
{
CRC(bitset<5>());
CRC(bitset<3>());
CRC(bitset<1>());

return 0;
}


----------

5
3
1
请按任意键继续. . .














muyingchi 2008-11-11
  • 打赏
  • 举报
回复
如果你的编译器仍然编译不过,就是编译器不支持这个模板特性。
muyingchi 2008-11-11
  • 打赏
  • 举报
回复
没发现有什么问题,可能是你bitset前面没加std

#include <bitset>


template<int i>
void Num(std::bitset<i>& bit)
{
int num = i;
}


int main()
{
Num(std::bitset<5>());
}

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧