免费注册 查看新帖 |

Chinaunix

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

请教:template的static member function 该怎么用? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-10-25 13:38 |只看该作者 |倒序浏览
一个singleton模板实现的练习
Sing.h
  1. #include <pthread.h>

  2. template <class T> class CTplSingleton
  3. {
  4. private:
  5.   static T _instance;
  6.   static pthread_mutex_t mutex;
  7. protected:
  8.   CTplSingleton<T>& operator=(const CTplSingleton<T>&);
  9.   CTplSingleton();
  10.   ~CTplSingleton();
  11. public:
  12.   static T& instance();
  13. };
复制代码


Sing.cpp
  1. #include "Sing.h"

  2. //static member data
  3. template<class T> pthread_mutex_t CTplSingleton<T>::mutex = PTHREAD_MUTEX_INITIALIZER;

  4. template<class T> T CTplSingleton<T>::_instance;

  5. //protected member  function
  6. template <class T> CTplSingleton<T>::CTplSingleton()
  7. {}

  8. template <class T> CTplSingleton<T>::~CTplSingleton()
  9. {}

  10. template <class T> CTplSingleton<T>& CTplSingleton<T>::operator=(const CTplSingleton<T>&)
  11. {}

  12. //public member function
  13. template <class T> T& CTplSingleton<T>::instance()
  14. {
  15.   if( 0 == _instance )
  16.   {
  17.     pthread_mutex_lock(&mutex);
  18.     if( 0 == _instance )
  19.     {
  20.       _instance = * new T;
  21.     }
  22.     pthread_mutex_unlock(&mutex);
  23.   }

  24.   return _instance;
  25. }
复制代码


demo.cpp
  1. #include "Sing.h"
  2. int main()
  3. {
  4.   int ref = CTplSingleton<int>::instance();
  5. }
复制代码


g++ demo.cpp Sing.cpp -Wall
demo.cpp: In function `int main()':
demo.cpp:65: warning: unused variable `int ref'
/tmp/ccV1tcJm.o(.text+0x11): In function `main':
: undefined reference to `CTplSingleton<int>::instance()'
collect2: ld returned 1 exit status

[root@VM template]# uname -a
Linux VM 2.4.20-8 #1 Thu Mar 13 17:54:28 EST 2003 i686 i686 i386 GNU/Linux

[root@VM template]# g++ --version
g++ (GCC) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
Copyright (C) 2002 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


静态成员函数应该怎么用的?

[ 本帖最后由 andyY 于 2006-10-25 13:40 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2006-10-25 13:55 |只看该作者
跟静态成员函数如何使用无关,类模板的成员函数的声明和定义都要放到头文件里,否则你无法在编译时进行模板展开,所以编译器会报告无法找到成员函数.

论坛徽章:
0
3 [报告]
发表于 2006-10-25 14:09 |只看该作者
哦,汗。谢谢!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP