Chinaunix首页 | 论坛 | 博客
  • 博客访问: 850846
  • 博文数量: 158
  • 博客积分: 4380
  • 博客等级: 上校
  • 技术积分: 2367
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-21 10:45
文章分类

全部博文(158)

文章存档

2012年(158)

我的朋友

分类: C/C++

2012-11-19 11:02:29

有关模板的语法很多很杂,无法一一列举,在此仅测试几个简单常用的语法。
以下有关模板的语法分别使用 gcc3.4.2、VC++6.0 和 Intel C++8.0 进行测试,GCC342和ICC都能完全通过测试,VC++6.0有部分通不过测试。

1. 模板类静态成员
template struct testClass {
    static int _data;
};
template<> int testClass::_data = 1;
template<> int testClass::_data = 2;
int main( void ) {
    cout << boolalpha << (1==testClass::_data) << endl;
    cout << boolalpha << (2==testClass::_data) << endl;
}

2. 模板类偏特化
template struct testClass {
    testClass() { cout << "I, O" << endl; }
};
template struct testClass {
    testClass() { cout << "T*, T*" << endl; }
};
template struct testClass {
    testClass() { cout << "const T*, T*" << endl; }
};
int main( void ) {
    testClass obj1;
    testClass obj2;
    testClass obj3;
}
[注]: VC++6 编译不通过

3. function template partial order
template struct testClass {
    void swap( testClass& ) { cout << "swap()" << endl; }
};
template inline void swap( testClass& x, testClass& y ) {
    x.swap( y );
}
int main( void ) {
    testClass obj1;
    testClass obj2;
    swap( obj1, obj2 );
}
[注]: VC++6 编译不通过

4. 类成员函数模板
struct testClass {
    template void mfun( const T& t ) {
        cout << t << endl;
    }
    template operator T() {
        return T();
    }
};
int main( void ) {
    testClass obj;
    obj.mfun( 1 );
    int i = obj;
    cout << i << endl;
}
[注]: 对于第二个成员函数模板,VC++6 运行异常

5. 缺省模板参数推导
template struct test {
    T a;
};
template > struct testClass {
    I b;
    O c;
};

6. 非类型模板参数
template struct testClass {
    T _t;
    testClass() : _t(n) {
    }
};
int main( void ) {
    testClass obj1;
    testClass obj2;
}

7. 空模板参数
template struct testClass;
template bool operator==( const testClass&, const testClass& ) {
    return false;
};
template struct testClass {
    friend bool operator== <>( const testClass&, const testClass& );
};
[注]: VC++6 编译不通过

8. 模板特化
template struct testClass {
};
template <> struct testClass {
};

9.
template