标签:C,C++,STL,学习,笔记
在SGI STL 中的config.h文件中有一些宏定义,这些宏定义可能会让你感到困惑,其实它们的主要作用就是为了区分不同编译器对C++ Standard的支持程度。
1. __STL_STATIC_TEMPLATE_MEMBER_BUG
# if __GNUC__ == 2 && __GNUC_MINOR__ <= 7
# define __STL_STATIC_TEMPLATE_MEMBER_BUG
# endif
# define __STL_STATIC_TEMPLATE_MEMBER_BUG
# endif
为什么会有这个定义?因为GNU C++编译器在2.7版本之前都存在这样一个bug :模板类static 的成员变量不能正常的初始化
template<class T>
class Test
{
public:
static T data;
};
int Test<int>::data = 5;
以上这一句看似很平常的初始化在GNU C++2.7版本之前不能得到预期想要的结果,在GNU C++2.8及以后版本中被修正
已经在VC2005中尝试,没有此BUG
2. __STL_CLASS_PARTIAL_SPECIALIZATION
正常的template class的使用当然大部分编译器都能支持,但是存在一些特殊的template class 的使用方法,举例如下:
template <class I, class O>
struct Test
{
Test() {cout << "I, O" << endl;}
};
template<class T>
struct Test<T*, T*>
{
Test() {cout << "T*, T*" << endl;}
};
template<class T>
struct Test<const T*, T*>
{
Test{cout << "const T*, T* << endl; }
}
void main()
{
Test<int, char> a;
Test<int*, int*> b;
Test<const int*, int*> c;
}
把编译器的对这种模板的支持叫做“类模板的偏特化”
已经在VC2005中尝试,支持此特性
[参考] 《C++ Template》 12.4 Class Template Partial Spetialization
3. __STL_FUNCTION_TMPL_PARTIAL_ORDER
该宏用来表示编译器是否支持函数模板偏序规则
[参考] 《C++ Template》 12.2 Partial Ordering of Overloaded function Templates
4. __STL_MEMBER_TEMPLATES
该宏用来表示编译器是否支持在template class中还存在template function
class alloc
{
};
template <class T, class Alloc=alloc>
class vector
{
typedef T value_type;
typedef value_type* interator;
template <class I>
void insert(interator position, I first, I last)
{
cout << "insert" << endl;
}
};
void main()
{
int ia[] = {0, 1, 2, 3, 4};
vector<int> a;
vector<int>::interator it;
a.insert(it, ia, ia+5);
}
5. __STL_LIMITED_DEFAULT_TEMPLATES
该宏用来表示编译器是否支持根据前一个模板参数来设置后一个模板参数的默认值
template <class T, class Alloc=alloc<T>>
class vector
{
...
};
6. __STL_NON_TYPE_TMPL_PARAM_BUG
该宏用来表示编译器是否支持非类型的模板参数
template <class T, class Alloc=allc, size_t bufsize>
class vector
{
...
};
7. __STL_NULL_TMPL_ARGS
# ifdef __STL_EXPLICIT_FUNCTION_TMPL_ARGS
# define __STL_NULL_TMPL_ARGS <>
# else
# define __STL_NULL_TMPL_ARGS
# endif
# define __STL_NULL_TMPL_ARGS <>
# else
# define __STL_NULL_TMPL_ARGS
# endif
8. __STL_TEMPLATE_NULL
# if defined(__STL_CLASS_PARTIAL_SPECIALIZATION) /
|| defined (__STL_PARTIAL_SPECIALIZATION_SYNTAX)
# define __STL_TEMPLATE_NULL template<>
# else
# define __STL_TEMPLATE_NULL
# endif
|| defined (__STL_PARTIAL_SPECIALIZATION_SYNTAX)
# define __STL_TEMPLATE_NULL template<>
# else
# define __STL_TEMPLATE_NULL
# endif
用于类模板的显式特化(class template explicit specialization)
template <class Key> struct hash {};
template <> struct hash<char> {};
template <> struct hash<unsignd char> {};