[c&cpp]const char* 和const char []在代码中如何识别各自类型
template<typename T> class _ischararray_;
template<typename T, int N>
class _ischararray_<T[N]> { public: static bool _ischararray(){return true;}};
template<typename T>
class _ischararray_<T*> { public: static bool _ischararray(){return false;}};
template<class T>
bool isCharArray(const T& x) { return _ischararray_<T>::_ischararray();}
1 #include <iostream> 2 using namespace std; 3 4 template<typename T> class _ischararray_; 5 6 template<typename T, int N> class _ischararray_<T[N]> 7 { 8 public: static bool _ischararray(){return true;} 9 }; 10 11 template<typename T> class _ischararray_<T*> 12 { 13 public: static bool _ischararray(){return false;} 14 }; 15 16 template<class T> bool isCharArray(const T& x) 17 { 18 return _ischararray_<T>::_ischararray(); 19 } 20 21 int _tmain(int argc, _TCHAR* argv[]) 22 { 23 const char* s1 = "12345"; 24 const char s2[] = "12345"; 25 isCharArray("12345")?cout<<"char []"<<endl:cout<<"char*"<<endl; //char [] 26 isCharArray(s1)?cout<<"char []"<<endl:cout<<"char*"<<endl; //char * 27 isCharArray(s2)?cout<<"char []"<<endl:cout<<"char*"<<endl; //char [] 28 29 return 0; 30 }
1 #include <iostream> 2 using namespace std; 3 4 namespace X 5 { 6 template<typename T, unsigned int SIZE> 7 bool IsArray (T (&a)[SIZE]) { return true; } 8 9 template<typename T> 10 bool IsArray (const T *&p) { return false; } 11 } 12 13 namespace Y 14 { 15 typedef char (&yes)[2]; 16 17 template<typename T, unsigned int SIZE> 18 yes IsArray (T (&a)[SIZE]); 19 20 template<typename T> 21 char IsArray (const T *&p); 22 } 23 24 int _tmain(int argc, _TCHAR* argv[]) 25 { 26 char s1[] = "hello"; 27 const char *s2 = "hello"; 28 #if 1 29 using namespace X; 30 if(true == IsArray(s2)) 31 throw 0; 32 if(false == IsArray("12345")) 33 throw 0; 34 if(false == IsArray(s1)) 35 throw 0; 36 #else 37 // 编译期间解决该问题 38 using namespace Y; 39 if(sizeof(IsArray(s2)) == sizeof(yes)) 40 throw 0; 41 if(sizeof(IsArray(s1)) != sizeof(yes)) 42 throw 0; 43 #endif 44 45 return 0; 46 }
template<typename T> bool isArray(T& arr) { if ((void*)&arr == (void*)arr) { return true; } return false; }
这种方法是更简单了点,不知道对不对?