C++模板编程中只特化模板类的一个成员函数
作者:网络转载 发布时间:[ 2015/7/14 13:23:06 ] 推荐标签:测试开发技术 开发语言
方法三:通过一个嵌套模板类的特化来实现
1 template <typename _Ty>
2 struct A
3 {
4 // 其他成员函数a
5 // 其他成员函数b
6 // ......
7 template <typename __Ty>
8 struct IsCharPType
9 {
10 const static bool b = false;
11 };
12
13 template<>
14 struct IsCharPType<char*>
15 {
16 const static bool b = true;
17 };
18
19 void func()
20 {
21 if (IsCharPType<_Ty>::b)
22 std::cout << "special type." << std::endl;
23 else
24 std::cout << "common type." << std::endl;
25 }
26 };
方法四:先定义一个嵌套的类模板,通过重载函数实现(函数的参数类型不同)
1 template <typename _Ty>
2 struct A
3 {
4 // 其他成员函数a
5 // 其他成员函数b
6 // ......
7 template <typename __Ty>
8 struct TypeClass
9 {
10 };
11
12 template <typename __Ty>
13 void funcImpl(const TypeClass<__Ty>&)
14 {
15 std::cout << "common type." << std::endl;
16 }
17
18 void funcImpl(const TypeClass<char*>&)
19 {
20 std::cout << "special type." << std::endl;
21 }
22
23 void func()
24 {
25 funcImpl(TypeClass<_Ty>());
26 }
27 };
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。

sales@spasvo.com