C++ Overloading functions and function templates - different behaviour? -
i have following code:
void a(const int*) { cout << "const int*" << endl; } void a(const int&) { cout << "const int&" << endl; } template <typename t> void b(const t*) { cout << "const t*" << endl; } template <typename t> void b(const t&) { cout << "const t&" << endl; } int main() { int* = nullptr; a(a); //output: const int* int* b = nullptr; b(b); //output: const t& return 0; }
a(a)
invoking function a(const int*)
b(b)
invoking template function b(const t&)
i not surprised template behaviour because of way overload resolution works. cannot explain why non-templated functions return opposite result (which kinda more intuitive).
is because non-templated functions there no need type deduced , considered exact match (adding const-ness permited?) ?
i not expert meta programming , things compiler doing (like overload resolution) , that's why bit confused.
in call non-template, passing pointer int. how call function expecting reference int? 2 different types. , yes, adding const permitted. if had overloaded on constness though:
void a(const int*) { cout << "const int*" << endl; } void a(int*) { cout << "int*" << endl; }
the non-const version selected better match.
with template, things different. remember pointers types too. valid deduce t
pointer type. when call b(b)
, compiler can use function:
template <typename t> void b(const t*) { cout << "const t*" << endl; }
in case t
must deduced int
, , const t*
becomes const int*
, pointer const int.
or compiler can choose function:
template <typename t> void b(const t&) { cout << "const t&" << endl; }
in case t
deduced int*
. , const t&
becomes int* const&
, is, reference const pointer int.
since, in second case, t
maps passed in (a pointer int), better match.
Comments
Post a Comment