博文
Concepts and Rvalue Reference : C++0x wi(2007-01-09 00:26:00)
摘要:Concepts and Rvalue Reference : C++0x will come
C++0x马上就要出来了。目前已经有许多提议已经大致成型,下面是最有可能出现在C++0x标准中的几个提议:
一、Concepts
Concept是BS极力要加入的一个新特性,用来对模板实例进行限制。例如
template<typename T>T max(T a, T b){ return a<b?b:a;}
typename关键字允许T是任何实例,但是max的代码却对T有隐含的限制:T必须能够用“<”进行比较。
再例如
template<typename InputIterator>InputIterator advance(InputIterator iter, size_t n){ //...}
InputIterator必须能够进行++操作。而考虑到advance对不同iterator的优化,可能需要iter+n的操作。
为了让编译器有效检查泛型参数的实例类型,加入Concept特性。
声明一个Concept:
auto concept LessThanCompareable<typename T>{ bool operator < (T, T); // 必须存在该函数};
auto关键字表示对运算符重载进行更广义的匹配,例如T::operator(const T&)也被认为符合上面的Concept
template<LessThanCompareable T>T max(T a, T b){ return a<b?b:a;}
或者使用where从句
template<typename T>T max(T a, T b)where LessThanCompareable<T>{ return a<b?b:a;}
where从句可以对多个参数进行联合检查:auto concept Convertible<typename U, typename......
分析类型的一个小实验(2006-08-01 21:10:00)
摘要:#include <cstdlib>#include <iostream>using namespace std;template<typename T>void print(const T &a) {cout << "unknown" << endl;}template<>void print<double>(const double &a) {cout << "double" << endl;}template<>void print<float>(const float &a) {cout << "float" << endl;}template<>void print<int>(const int &a) {cout << "int" << endl;}int main(int argc, char *argv[]){ char a;int b;float c;short int d; print((c*b+a)*d); system("PAUSE"); return 0;}float请按任意键继续. . .......
模板的妙用(2006-08-01 20:59:00)
摘要:#include <cstdlib>#include <iostream>using namespace std;template<typename T, size_t n>bool __is_array(T (&a)[n]) {return true;}bool __is_array(...) {return false;}template<typename T>bool IsArray(T &a){ return __is_array(a);}template<typename T, size_t n>void Test( T (&array)[n], bool first = false);template<typename T, size_t n>void Test_Shadow( T (&array)[n]);template<typename T>void Test( T& ){}template<typename T>void Test_Shadow( T& ){}template<typename T, size_t n>void Test( T (&array)[n], bool first ){ if(first) cout << "the array is like A"; &n......
