首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

用模板技术判断一个类型是否为类解决思路

2012-05-03 
用模板技术判断一个类型是否为类以下代码是从《C++ Templates》第15.2.2节抄过来的,但是无论在VS2010还是在g

用模板技术判断一个类型是否为类
以下代码是从《C++ Templates》第15.2.2节抄过来的,但是无论在VS2010还是在gcc上都无法通过编译。有没有对模板比较了解的朋友知道这是怎么回事?

C/C++ code
// traits/isclasst.hpptemplate <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 };};


C/C++ code
//traits/isclasst.cpp#include "isclasst.hpp"#include <iostream>using namespace std;class MyClass{};struct MyStruct{};union MyUnion{};void myfunc(){}enum E { e1 } e;// Check by passing type as template argumenttemplate <typename T>void check(){    if (IsClassT<T>::Yes)    {        cout << " IsClassT " << endl;    }    else    {        cout << " !IsClassT " << endl;    }}// Check by passing type as function call argumenttemplate <typename T>void checkT(T){    check<T>();}int main(){    cout << "int:       ";    check<int>();    cout << "MyClass:   ";    check<MyClass>();    cout << "MyStruct:  ";    MyStruct s;    checkT(s);    cout << "MyUnion:   ";    check<MyUnion>();    cout << "enum:      ";    checkT(e);    cout << "myfunc():  ";    checkT(myfunc);}


[解决办法]
探讨

引用:

引用:

我用 g+=-4.4 都能编译,楼主具体什么错误啊?


看来是我用的gcc老了——才4.1.2。

gcc上的错误是:

isclasst.hpp:17: error: expected primary-expression before ‘>’ token

VS2010下的错误可以用“井喷”来形容,主要是无……

热点排行