我有一个模板化的函数,它接受一个数组引用作为参数:
template<typename T, int arrSize>
void foo(T (&pArr)[arrSize]) {
cout << "base template function" << endl;
}
我想为c字符串专门化这个函数:
template<const char *, int arrSize>
void foo(const char * (&pArr)[arrSize]) {
cout << "specialized template function" << endl;
}
我尝试实例化基和专门化:
int main(int argc, const char **argv) {
float nums[] = {0.3, 0.2, 0.11};
const char *words[] = {"word1", "word2"};
foo(nums);
foo(words);
}
但我似乎只得到基本实例化:
./foo
base template function
base template function
我已经在Mac上使用clang++ + -std=c++17编译了这个。
尝试:
template<int arrSize>
void foo(const char * (&pArr)[arrSize]);
你定义了一个重载,期望一个不可演绎的char const*
非类型参数。
问题第二个重载的您提供的函数模板有一个类型为const char*
的非类型模板参数,不能从函数参数中推导出来。因此,要调用这个重载版本,必须显式地提供与此非类型形参对应的模板实参。
这只是删除了第一个非类型模板参数,如下所示:
template<typename T, int arrSize>
void foo(T (&pArr)[arrSize]) {
std::cout << "base template function" << std::endl;
}
//overload for C-strings
template< int arrSize>
void foo(const char (&pArr)[arrSize]) {
std::cout << "single C-string overloaded version" << std::endl;
}
//overload for array of pointers to C-strings
template<std::size_t arrSize>
void foo(const char*(&pArr)[arrSize])
{
std::cout<<" array of pointers to C-string version"<<std::endl;
}
int main(int argc, const char **argv) {
float nums[] = {0.3, 0.2, 0.11};
const char words[] = {"word1"};
const char* wordPtrs[] = {"word1", "word2"};
foo(nums); //calls base
foo(words);//calls single C-string version
foo(wordPtrs);//calls array of pointers to C-string version
}
演示还要注意,函数模板不能部分特化,但可以完全特化,也可以重载。