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;