用模板区分内建类型和非内建类型,函数传值时分别传入值或者引用~

huntrose 2009-03-06 05:07:49


#include <iostream>

using namespace std;

template<typename type_t>
struct ParamType {
typedef type_t& type;
};

template<>
struct ParamType<int> {
typedef int type;
};

template<typename t>
void print(typename ParamType<t>::type i)
{
cout<<i<<endl;
}

int main()
{
int i = 10;
print(i);

return 0;
}

G:\Projects\ParamTest\main.cpp|29|error: no matching function for call to `print(int&)'|



我想达到的目的是,在内建类型传值的时候使用值传递
在自定义类型传值的时候使用引用传值
这里使用模板struct ParamType来得到类型
非内建类型使用 ParamType<Non_Buildin_Type>::type 得到的是 Non_Buildin_Type&
偏特化内建类型的所有类型后,比如这个int,得到的就是int
请各位教一教,有什么现成的资料发给链接也好~
...全文
143 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
tangshuiling 2009-03-06
  • 打赏
  • 举报
回复

既然已经特化了,就特殊对待呗.
print<int>(i);
taodm 2009-03-06
  • 打赏
  • 举报
回复
boost的源码在那放着呢。
不过,没认真看过《modern c++ design》或者《C++ templates》宝典,一般是搞不定这个问题的。
huntrose 2009-03-06
  • 打赏
  • 举报
回复
to 4楼
我的编译错误怎么解决? 我已经特化了int的版本了啊?
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 akirya 的回复:]
特化呗
多弄几个template <>
struct ParamType <int> {
typedef int type;
};
就成了.
[/Quote]
up
huntrose 2009-03-06
  • 打赏
  • 举报
回复
to taodm... 我只是想知道是怎么造的~
taodm 2009-03-06
  • 打赏
  • 举报
回复
兄弟啊,自己先google boost的中文版资料吧。
这轮子不需要重复造的。
  • 打赏
  • 举报
回复
特化呗
多弄几个template<>
struct ParamType<int> {
typedef int type;
};
就成了.

65,210

社区成员

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

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