type_traits这样可以吗

ligang17596 2005-02-16 09:10:16
以下是源代码
#include<iostream>
#define null template<>

using namespace std;

struct a_type{};
struct b_type{};
struct c_type{};

void output(int i, a_type)
{
cout << i << endl;
}

void output(int *j, b_type)
{
cout << *j << endl;
}

void output(int &k,c_type)
{
cout << k << endl;
}

template<class T>
struct type_traits
{
};


null struct type_traits<int>
{
typedef a_type atype;
};

null struct type_traits<int *>
{
typedef b_type btype;
};

null struct type_traits<int &>
{
typedef c_type ctype;
};


int main()
{
int t = 2;
int *i;
i = &t;
int &d = t;
cout << t << endl;
cout << d << endl;
typedef type_traits<int>::atype aatype;
typedef type_traits<int *>::btype bbtype;
typedef type_traits<int &>::ctype cctype;
output(t, aatype());
output(i, bbtype());
output(d, cctype());

return 0;
}
结果如下:
2
2
2
2
2
...全文
79 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Mephisto_76 2005-02-17
  • 打赏
  • 举报
回复
将type_traits 中的 atype、btype、ctype都改为type,然后就直接使用type_traits<int>::type, type_traits<int*>::type, type_traist<int&>::type 就成了。不需要使用这么多typedef。traits的意思就是使不同类型的traits中的字面相同的类型代表不同的意义。如果字面本来就不一样,就不需要使用traits了。

而且也不应该使用null,要使用template<> struct type_traits<int>之类的形式。
ilovevc 2005-02-16
  • 打赏
  • 举报
回复
你这种用法不对,根本没有理解traits的作用。
看你的main函数中,你还要让使用者typedef一堆东西,它还不如直接调用某个特定的函数算了。

而且null 这些东西可以编译通过吗?
ligang17596 2005-02-16
  • 打赏
  • 举报
回复
不好意思 是关于traits的问题
huyuhui123 2005-02-16
  • 打赏
  • 举报
回复
简化你要问的问题行吗,没有时间看这么多

64,648

社区成员

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

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