Question

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?

Was it helpful?

Solution

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,

(...)

OTHER TIPS

The compiler will prefer the specialized version whenever possible.

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top