C++模板函数显式特化报错:无法特化实体的问题修复
修复函数模板特化的编译错误
问题
编译代码时触发错误:function template "T smaller(const T&first, const T&second)" is not an entity that can be explicitly specialized,原代码如下:
main.cpp
/* * 15.1.3 : Using function template * Specialization */ #include <cstring> #include <iostream> #include <string> using namespace std; // template function template<typename T> T smaller(const T& first, const T& second) { if (first < second) { return first; } return second; } // specialization of template function template<> const char* smaller(const(const char*) & first, const(const char*) & second) { if (strcmp(first, second) < 0) { return first; } return second; } int main() { // calling template with two string objects string str1 = "Hello"; string str2 = "Hi"; cout << "Smaller(Hello,Hi) : " << smaller(str1, str2) << endl; // calling template function with two C-string objects const char* s1 = "Bye"; const char* s2 = "Bye Bye"; cout << "Smaller (Bye, Bye Bye) : " << smaller(s1, s2) << endl; return 0; }
错误原因
问题出在C字符串版本的模板特化代码:const(const char*) &是非法的类型声明语法,编译器无法识别这种写法,导致无法匹配原模板函数完成特化,因此抛出错误。
修复方案
方案1:修正模板特化的语法
将特化的参数类型修正为合法的const char* const&(表示指向const字符的const指针的引用),代码如下:
/* * 15.1.3 : Using function template * Specialization */ #include <cstring> #include <iostream> #include <string> using namespace std; // 模板函数 template<typename T> T smaller(const T& first, const T& second) { return first < second ? first : second; } // 针对const char*的模板特化 template<> const char* smaller(const char* const& first, const char* const& second) { return strcmp(first, second) < 0 ? first : second; } int main() { string str1 = "Hello"; string str2 = "Hi"; cout << "Smaller(Hello,Hi) : " << smaller(str1, str2) << endl; const char* s1 = "Bye"; const char* s2 = "Bye Bye"; cout << "Smaller (Bye, Bye Bye) : " << smaller(s1, s2) << endl; return 0; }
方案2:使用函数重载替代模板特化
相比模板特化,直接重载函数的写法更简洁直观,且避免语法陷阱,代码如下:
/* * 15.1.3 : Using function template * Specialization */ #include <cstring> #include <iostream> #include <string> using namespace std; // 模板函数 template<typename T> T smaller(const T& first, const T& second) { return first < second ? first : second; } // 直接重载C字符串版本 const char* smaller(const char* first, const char* second) { return strcmp(first, second) < 0 ? first : second; } int main() { string str1 = "Hello"; string str2 = "Hi"; cout << "Smaller(Hello,Hi) : " << smaller(str1, str2) << endl; const char* s1 = "Bye"; const char* s2 = "Bye Bye"; cout << "Smaller (Bye, Bye Bye) : " << smaller(s1, s2) << endl; return 0; }
内容的提问来源于stack exchange,提问作者Hyeri1ee
相关产品推荐
相关产品推荐

