1.写一个通用函数:作用是在数组里找到和value值相同的值的索引
template<typename T> size_t Find(T& value , T *array,size_t size) { for(size_t i = 0;i < size;++i) { if(array[i] == value) { return i; } } std::cout << "NOT FOUND" << std::endl; return -1; } int main() { int array[] = {1,2,3,4,5}; int value = 3; size_t size = sizeof(array) / sizeof(int); size_t index = Find(value,array,size); if(index!= (-1)) { std::cout << index << std::endl; } return 0; }
2.函数模板可以特例化
template<typename T> size_t Find(T& value , T*array,size_t size) { for(size_t i = 0;i < size;++i) { if(array[i] == value) { return i; } } std::cout << "NOT FOUND" << std::endl; return -1; } template<> size_t Find<const char*>(const char *& value , const char **array,size_t size) { for(size_t i = 0;i < size;++i) { if(strcmp(array[i],value) == 0) { return i; } } std::cout << "NOT FOUND" << std::endl; return -1; } int main() {const char * arr[] = {"one" , "two" , "three" , "four"}; const char * value = "oks"; size_t size = sizeof(arr) / sizeof(char*); size_t index = Find<const char*>(value,arr,size); if(index != (-1)) { std::cout << index << std::endl; } return 0; }
记得一定要实现定义好原模板Find();否则特例化会失败;