I have the following code:
template<class A, class B>
void test(A& a, const B* b)
{ std::cout << "hi" << std::endl; }
template<class A, class B>
void test(A& a, const B** b)
{ std::cout << "hello" << std::endl; }
class TestClass
{};
int main()
{
int a = 5;
TestClass b;
TestClass* c = &b;
test(a, &c);
return 0;
}
Somehow the output is "hi" although it seems that better match would be the second template function. When I remove consts as the qualifiers to B* and B** then I get "hello" which corresponds to the second template function. How does the compiler choose the function to call in this case? Thanks!
Given that there is no conversion from T** to T const** the second isn't a match at all (there is no such conversion because it would allow nonconst access to a const object). There is a conversion from T** to T* const*, however. Thus, the corresponding overload is the only viable and used one.
&c is a TestClass** which may be promoted to TestClass* const * but not to const TestClass**.
You may force the error by explicitly using test<int, TestClass>(a, &c); which will show you the impossible conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With