No viable conversion from 'bool' to 'std::string'

后端 未结 4 2081
感动是毒
感动是毒 2021-01-29 13:44

I have some code that looks like this:

static std::string Foo(const std::string& blah)
{
   if ( someWierdEdgeCase() ){
      return false;  // <-- this l         


        
相关标签:
4条回答
  • 2021-01-29 14:06

    This:

      return false;  // <-- this line has a compiler error
    

    There is no standard way to convert bool to std::string (please correct me if there is or was something special in gcc (the old XCode mac compiler)). This means that your code base used to contain explicit code to convert the bool to string.

    If it is not compiling now this suggests this conversion was removed from your code base.

    A couple of people of suggested alternatives. But I doubt any of these are going to work. As the old code had a depedency on how it used to work. So making any specific recomendation will depend on working out how the old code compiled and what it returned when someWierdEdgeCase() is true. Basically you need to replicate this behavior.

    Otherwise you need to hunt down all used cases in your code and change the behavior to match the new behavior. In this case I would change the name of the function. Re-Compile and see where the code breaks and check the behavior at each location and make sure it behaves the same.

    0 讨论(0)
  • 2021-01-29 14:15
    static std::string Foo(const std::string& blah)
    {
       std::string resourcePath = "";
       if ( someWierdEdgeCase() ){
          return resourcePath; // <-- Now you're returning a string
       }
    
       resourcePath.append("/assets/");
       return resourcePath; 
    }  
    
    0 讨论(0)
  • 2021-01-29 14:20

    If you need the return type to be - for whatever reason - not always present, return by pointer, instead of returning by value.

    static yourType* Foo(const std::string& blah){
       if ( someWierdEdgeCase() ){
          return 0;
       }
    }
    

    Then you can test and assign the function in the same line

    yourType* result;
    if(result = Foo("something")){
      // the result was correct
    

    Of course - since your function returns a std::string, you can return an empty string (""), or - also independent of the return type - throw an exception.

    0 讨论(0)
  • 2021-01-29 14:20

    I had same issue that with the fact that my interface file and implementation file were using different data types in method declaration.Putting same data type on both place in method declaration error went away.

    0 讨论(0)
提交回复
热议问题