I have two files: error.h and error.cpp. Compiling with
g++ -std=c++0x
gives me an error:
error.cpp:9:33:**call of overloaded "to_string(char*&)" is ambiguous**
How can i fix this problem?
error.h:
1 #ifndef ERROR_H_GUARD
2 #define ERROR_H_GUARD
4 #include <string>
6 class Error {
7 public:
8 Error(int pos, std::string& msg);
10 Error(int pos, char* msg);
12 const char* what() throw();
14 private:
15 std::string msg;
17 void setMsg(int pos, std::string& msg);
18 };
19
20 #endif
error.cpp:
2 #include "error.h"
4 Error::Error(int pos, std::string& msg){
5 setMsg(pos, msg);
6 }
8 Error::Error(int pos, char* msg) {
9 setMsg(pos, std::to_string(msg));
10 }
12 const char* Error::what() throw() {
13 return msg.c_str();
14 }
16 void Error::setMsg(int pos, std::string& msg){
17 this->msg = std::to_string(pos) + msg + std::string("\n") + std::string(pos - 1, ' ') + std::string("^");
18 }
to_string()is used to convert something which is not a string (e.g. along, anint, etc.) into astring. You have achar*, which is a C string, and what you want to do is to create astringobject out of it, not convert it.Your compiler complains about ambiguity because it cannot find a version of
to_string()for the type you are passing to it (char*), which makes sense, considering the purpose of that function.If you declared your parameter
string const&rather thanstring&in the corresponding overload ofsetMsg()(and in the constructor ofErroras well), you could directly invoke it by passing C strings: a temporary of typestringwould be created automatically and bound to the argument ofsetMsg().This way you would even get rid of the specific overload of
setMsg()for C strings, which in fact does nothing but forwarding.