C++模板:为什么不调用专用函数?
模板函数作为一般和特殊情况存在:
#include <string>
#include <iostream>
using namespace std;
// General case
template<typename X> void whichOneIsLarger(X a, X b) {
(a > b) ? cout << "x [" << a << "] is larger than y [" << b << "]" : cout << "y [" << b << "] is larger than x [" << a << "]" << endl;
}
// Specialization
template<> void whichOneIsLarger<string>(string a, string b) {
(a.size() > b.size()) ? cout << "x [" << a << "] is longer than y [" << b << "]" : cout << "y [" << b << "] is longer than x [" << a << "]" << endl;
}
使用字符串调用它时,我希望两个调用都使用特化,为什么不是这样?
int main()
{
string hallo = "hallo"; string world = "world";
whichOneIsLarger(hallo, world); // <-- Calls specialization
whichOneIsLarger("hallo", "world"); // <-- Calls general case
}
回答
因为"hallo"和"world"不是std::strings,而是c 样式的字符串文字(具有类型const char[6]并且可以衰减为const char*)。
你可以std::string明确地通过,
whichOneIsLarger(std::string("hallo"), std::string("world"));
或者使用std::string文字(C++14 起):
using namespace std::string_literals;
whichOneIsLarger("hallo"s, "world"s);
如果你想用 c 风格的字符串文字来指定,你可以
template<> void whichOneIsLarger<const char*>(const char* a, const char* b)
请注意,您必须提供特殊的执行const char*。
- `const char *` ... the `const` is needed