C++中export关键字的尴尬处境-2
帐 号: 注册帐号
密 码:  找回密码
      记住用户名和密码
C++中export关键字的尴尬处境-2

参考:

《VS 2010 并不支持 C++ 0x 标准中的 extern template》

《C++ 0x(C++ 09)新标准全部革新提案文档列表》

模板具体化可以分离编译,且要是不以内联函数实现成员函数时,则为了在多个文件中使用,则必须分开,在另一个文件中定义成员函数。

示例。

头文件Stack.h

#ifndef STACK_H_
#define STACK_H_

namespace util
{

   //模板类 
   template
   class Stack
   {
    private:
     enum{SIZE=10};
     T a[SIZE];
     int top;
    public:
     Stack():top(0){}

     bool isEmpty()const;
     bool isFull()const;
     bool push(const T el);
     bool pop(T &p);
   };

   //模板具体化
   template <>
   class Stack
   {
    private:
     enum{SIZE=10};
     char * a[SIZE];
     int top;
    public:
     Stack():top(0){}

     bool isEmpty()const;
     bool isFull()const;
     bool push( char * const el); //模板的类型是指针,故此处因为常指针
     bool pop(char * &p);
   };
   
   //编译器没实现关键字export,故必须在此处实现
   template
   bool Stack::isEmpty()const
   {
     return 0==top;
   }
   template
   bool Stack::isFull()const
   {
     return SIZE==top;
   }
   template
   bool Stack::push(T el)
   {
     if(top>=SIZE)
      return false;
     a[top++]=el;
     return true;
   }
   template
   bool Stack::pop(T &p)
   {
     if(0 == top)
      return false;
     p=a[--top];
     return true;
   }

    
   //模板实例化(具有内部连接性,故可在头文件中定义实例化类
   
   template class Stack
   // template class Stack; //会重复定义,故注释掉
   template class Stack;

}
#endif

模板具体化实现Stack.cpp

在Vc中可以编译连接通过,在G++中认为成员函数不匹配,高手知道,还望告知

#include
#include"Stack.h"


namespace util
{
template <>
   bool Stack::isEmpty()const
   {
    return 0==top;

   }


template <>
    bool Stack::isFull()const
    {
     return SIZE==top;
}
    
template <>
    bool Stack::push(char * const el)
    {
     if(top>=SIZE)
      return false;
     a[top++]=el;
     return true;
    }

template <>
    bool Stack::pop(char * &p)
    {
using std::cout;
using std::endl;
     if(0 == top)
      return false;
     p=a[--top];
     cout<<"具体化"<
     return true;
    }
}
测试main.cpp

#include
#include"Stack.h"
using namespace util;
typedef Stack stack;

int main()
{
using std::cout;
using std::endl;
stack s;
int a[]={2,3,4,5,7,8};
int i=0;
for( i=0;i
{
   cout<
   if(!s.isFull())
       s.push(a[i]);
}
int tmp=0;
cout<
while(s.pop(tmp))
{
   cout<
}
cout<
Stack s1;
char t[]="bao";
char t1[]="af";
char t2[]="trqtr";
char *ch[]={t,t1,t2};
for( i=0;i
{
   cout<
   if(!s1.isFull())
       s1.push(ch[i]);
}
char *tmp1;
cout<
while(s1.pop(tmp1))
{
   cout<
}
cout<
Stack s2;
const char *ch1[]={"faf","ta","tet"};
for( i=0;i
{
   cout<
   if(!s2.isFull())
       s2.push(ch1[i]);
}
const char *tmp2;
cout<
while(s2.pop(tmp2))
{
   cout<
}
return 0;
}

参考文献:

http://hi.baidu.com/taoshui123/item/d971f088a337a056e63d19eb

copyright:2016-2020|邮箱:imalib@vip.163.com

蜀ICP备16020986号