免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1228 | 回复: 2
打印 上一主题 下一主题

[C++] 关于模版问题-->c++_templates_complete_guide [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-12-30 16:31 |只看该作者 |倒序浏览
请问c++_templates_complete_guide中的例子:
判断templates parameter是否为类,怎么编译不过?

#include "windows.h"
#include "iostream"

template<typename T>
class IsClassT {
  private:
    typedef char One;
    typedef struct { char a[2]; } Two;
    template<typename C> static One test(int C::*);
    template<typename C> static Two test();
  public:
    enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
    enum { No = !Yes };
};


class MyClass {
};

struct MyStruct {
};

union MyUnion {
};

void myfunc()
{
}

enum E{e1} e;

// check by passing type as template argument
template <typename T>
void check()
{
    if (IsClassT<T>::Yes) {
        std::cout << " IsClassT " << std::endl;
    }
    else {
        std::cout << " !IsClassT " << std::endl;
    }
}

// check by passing type as function call argument
template <typename T>
void checkT (T)
{
    check<T>();
}

int main()
{
    std::cout << "int: ";
    check<int>();

    std::cout << "MyClass: ";
    check<MyClass>();

    std::cout << "MyStruct:";
    MyStruct s;
    checkT(s);

    std::cout << "MyUnion: ";
    check<MyUnion>();

    std::cout << "enum:    ";
    checkT(e);

    std::cout << "myfunc():";
    checkT(myfunc);
}

论坛徽章:
0
2 [报告]
发表于 2006-12-30 22:12 |只看该作者
enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; 定义在 class IsClassT 中,在 class IsClassT 域中使用其任何成员不再需要在前面加上 IsClassT 的限定。或许在旧版的编译器(GCC)中上述用法可以通过,但是新版本把它作为一个非规范的用法而报错。因此,可能要改成这样:enum { Yes = sizeof(test<T>(0)) == 1 };

另外,template<typename C> static Two test(); 应该改为 template<typename C> static Two test(...);

[ 本帖最后由 whyglinux 于 2006-12-30 22:22 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2006-12-31 09:14 |只看该作者

非常感谢版主

按照whyglinux 的建议修改后,在
vc7.0 编译通过
g++ v4.1 linux 编译通过

g++ v2.95 unixware 编译不通过
a.cpp:13: warning: all member functions in class `IsClassT<T>' are private
a.cpp: In instantiation of `IsClassT<int>':
a.cpp:35:   instantiated from `check<int>()'
a.cpp:53:   instantiated from here
a.cpp:35: invalid use of undefined type `class IsClassT<int>'
a.cpp:13: forward declaration of `class IsClassT<int>'
a.cpp: In instantiation of `IsClassT<MyClass>':
a.cpp:35:   instantiated from `check<MyClass>()'
a.cpp:56:   instantiated from here
a.cpp:35: invalid use of undefined type `class IsClassT<MyClass>'
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP