简体   繁体   中英

Overload Resolution between func(const char*) and func(std::string&)

I have two functions:

int func(const std::string& str) { return func(str.c_str()); }
int func(const char* str) { /* ... */ }

If I call func(std::string("abcdef")); first function ( const std::string& ) call recursively itself, not a const char* because type conversion.

I can use Forward Declaration :

int func(const char* str);
int func(const std::string& str) { return func(str.c_str()); }
int func(const char* str) { /* ... */ }

or change functions definitions order:

int func(const char* str) { /* ... */ }
int func(const std::string& str) { return func(str.c_str()); }

and it works.

But is there another way for Overload Resolution ?

To exclude implicit type conversions from overload resolution you should make template functions that only accept exact type matches. (SFINAE) eg

template<typename type_t> 
auto func(const type_t& string) 
    -> std::enable_if_t<std::is_same_v<std::string,type_t>,int> 
{ 
} 

This will resolve to a function returning an int only when std::string and type_t exactly match (without conversions)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM