c++ - Function overloading for const char*, const char(&)[N] and std::string -
what want achieve have overloads of function work string literals , std::string, produce compile time error const char* parameters. following code want:
#include <iostream> #include <string> void foo(const char *& str) = delete; void foo(const std::string& str) { std::cout << "in overload const std::string& : " << str << std::endl; } template<size_t n> void foo(const char (& str)[n]) { std::cout << "in overload array " << n << " elements : " << str << std::endl; } int main() { const char* ptr = "ptr const"; const char* const c_ptr = "const ptr const"; const char arr[] = "const array"; std::string cppstr = "cpp string"; foo("string literal"); //foo(ptr); //<- compile time error foo(c_ptr); //<- should produce error foo(arr); //<- ideally should produce error foo(cppstr); } i'm not happy, compiles char array variable, think there no way around if want accept string literals (if there is, please tell me)
what avoid however, std::string overload accepts const char * const variables. unfortunately, can't declare deleted overload takes const char * const& parameter, because match string literal.
any idea, how can make foo(c_ptr) produce compile-time error without affecting other overloads?
this code needed (except array - literals arrays, can't separate them)
#include <cstddef> #include <string> template <class t> void foo(const t* const & str) = delete; void foo(const std::string& str); template<std::size_t n> void foo(const char (& str)[n]); int main() { const char* ptr = "ptr const"; const char* const c_ptr = "const ptr const"; const char arr[] = "const array"; std::string cppstr = "cpp string"; foo("string literal"); //foo(ptr); //<- compile time error // foo(c_ptr); //<- should produce error foo(arr); //<- ideally should produce error foo(cppstr); }
Comments
Post a Comment