我编写了以下代码作为关于函数模板和模板特化的练习。它是一个计算给定类型的对象在 a 中的数量的函数vector
:
template <typename T>
int function(const std::vector<T> &vec, T val) {
int count = 0;
for(typename std::vector<T>::const_iterator it = vec.begin(); it != vec.end(); ++it)
if(*it == val)
++count;
return count;
}
template <>
int function(const std::vector<const char*> &vec, const char* val) {
int count = 0;
for(std::vector<const char*>::const_iterator it = vec.begin(); it != vec.end(); ++it) {
if (std::string(*it) == std::string(val))
++count;
}
return count;
}
我在专业化中编写代码是因为我想知道单词中的每个字符是否与给定的文字相同。令我惊讶的是,如果我注释掉特化并让编译器实例化原始模板,它甚至适用于 const char 数组:
int main() {
std::vector<const char*> cvec = {"hi", "hi", "hallo", "hej", "hej", "hi", "hej", "hej", "hej"};
std::cout << function(cvec, "hej") << std::endl;
}
怎么可能?