#include <iostream> using namespace std; 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(); } int _tmain(int argc, _TCHAR* argv[]) { const char* s1 = "12345"; const char s2[] = "12345"; isCharArray("12345")?cout<<"char []"<<endl:cout<<"char*"<<endl; //char [] isCharArray(s1)?cout<<"char []"<<endl:cout<<"char*"<<endl; //char * isCharArray(s2)?cout<<"char []"<<endl:cout<<"char*"<<endl; //char [] return 0; }
或者下面这段我没有看懂的代码,麻烦大牛们帮忙解释一下下面的代码段:
#include <iostream> using namespace std; namespace X { template<typename T, unsigned int SIZE> bool IsArray (T (&a)[SIZE]) { return true; } template<typename T> bool IsArray (const T *&p) { return false; } } namespace Y { typedef char (&yes)[2]; template<typename T, unsigned int SIZE> yes IsArray (T (&a)[SIZE]); template<typename T> char IsArray (const T *&p); } int _tmain(int argc, _TCHAR* argv[]) { char s1[] = "hello"; const char *s2 = "hello"; #if 1 using namespace X; if(true == IsArray(s2)) throw 0; if(false == IsArray("12345")) throw 0; if(false == IsArray(s1)) throw 0; #else // 编译期间解决该问题 using namespace Y; if(sizeof(IsArray(s2)) == sizeof(yes)) throw 0; if(sizeof(IsArray(s1)) != sizeof(yes)) throw 0; #endif return 0; }