Consider these are both inside a class declaration:
template<class V>
bool tryGetValue(const string &key,V& value) const { ... }
bool tryGetValue(const string &key,bool& value) const { ... }
What will the compiler do here?
编译器会尽可能选择专用版本。
It will prefer the non-template method.
From 14.8.3:
Note also that 13.3.3 specifies that a non-template function will be given preference over a template specialization if the two functions are otherwise equally good candidates for an overload match.
And a part from 13.3.3:
Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then
(...)
- F1 is a non-template function and F2 is a function template specialization, or, if not that,
(...)
The compile will choose the best matching overload.
template<class V>
bool tryGetValue(const std::string &key,V& value) {
return false;
}
// Overload (no specilaization)
bool tryGetValue(const std::string &key,bool& value) {
return true;
}
int main()
{
std::string s = "Hello";
int i = 1;
bool b = true;
std::cout
<< "Template: "
<< ((tryGetValue(s, i) == false) ? "Success" : "Failure") << std::endl;
std::cout
<< "No Template: " << (tryGetValue(s, b) ? "Success" : "Failure") << std::endl;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.