Is it safe to overload char* and std::string?

后端 未结 2 1532
轻奢々
轻奢々 2021-02-10 17:05

I have just read about the overloading functions on a beginner book. Just out of curiosity I \'d like to ask whether it is safe to overload between char* and std::string.

2条回答
  •  情书的邮戳
    2021-02-10 17:33

    Short Answer: Perfectly safe. Consider the following uses:

    foo("bar");//uses c string 
    foo(std::string("bar") );//uses std::string
    char* bar = "bar";
    foo(bar);//uses c string
    std::string bar_string = "bar";
    foo(bar_string);//uses std::string
    foo(bar_string.c_str()); //uses c string
    

    Word of warning, some compilers (namely those with c++11 enabled) require the const keyword in parameter specification in order to allow temporary strings to be used.

    For instance, in order to get this: foo("bar"); You need this: void foo(const char* bar);

提交回复
热议问题