C++11 Lambda functions implicit conversion to bool vs. std::function

前端 未结 4 734
时光取名叫无心
时光取名叫无心 2021-01-12 05:36

Consider this simple example code:

#include 
#include 

void f(bool _switch) {
    std::cout << \"Nothing really\" &l         


        
4条回答
  •  被撕碎了的回忆
    2021-01-12 06:10

    You can get rid of the implicit conversion by creating a helper class

    #include 
    #include 
    
    struct Boolean { 
        bool state; 
        Boolean(bool b):state(b){} 
        operator bool(){ return state; } 
    };
    void f(Boolean _switch) {
        std::cout << "Nothing really " << _switch << std::endl;
    }
    
    void f(std::function _f) {
        std::cout << "Nothing really, too" << std::endl;
    }
    
    int main ( int argc, char* argv[] ) {
        f([](int _idx){ return 7.9;});
        f(true);
        return 0;
    }
    

    Should you ever want to call f with eg. a pointer and expect it to call the first overload you will have to cast it to either bool or add a corresponding constructor / cast to the helper class though.

提交回复
热议问题