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 (with t = char*) whereas has promote const char* called void func (const char *buf).

the compiler prefers use exact match wherever possible.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -