Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template overloading plus pointer to pointer

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!

like image 238
hovnatan Avatar asked Jun 09 '14 11:06

hovnatan


2 Answers

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.

like image 104
Dietmar Kühl Avatar answered Sep 24 '22 02:09

Dietmar Kühl


&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.

like image 38
Jarod42 Avatar answered Sep 22 '22 02:09

Jarod42