c++ - Why can't a specialized template function accept both a type and it's constant version? -
if t type, why can normal function accept both t , const t specialized template function cannot? mean programmer has type more code defeats purpose of using templates?
struct s {       void func(const char *buf)     {         cout << "func(const char *)" << endl;     }       void func(const wchar_t *buf)     {         cout << "func(const wchar_t *)" << endl;     }  }; output: 2 different functions called t , const t when t char*/wchar_t*
func(const char *) func(const wchar_t *) func(const char *) func(const wchar_t *) the same templates:
struct ss {     template<typename t>     void func (t t)     {         cout << "func (t)" << endl;      }      template<>     void func (const char *buf)     {         cout << "func (const char *)" << endl;     }      template<>     void func(const wchar_t *buf)     {         cout << "func (const wchar_t *)" << endl;     }  }; output: 3 different functions called t , const t when t char*/wchar_t*
func (const char *) func (const wchar_t *) func (t) func (t) 
to quote jarod42's comment:
with
char *,void func (t t)exact match (witht = char*) whereas has promoteconst char*calledvoid func (const char *buf).
the compiler prefers use exact match wherever possible.
Comments
Post a Comment