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

前端 未结 4 768
时光取名叫无心
时光取名叫无心 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:20

    One more option to Vaughn Cato's answer:

    template
    void f(F _f) {
        std::cout << "Nothing really, too: " << _f(3) << std::endl;
    }
    

    Now the second overload is a template, so it is chosen for a lambda (or anything), and the first is chosen for bool. So calling f is no more complex than needed.

    But, one problem with that is if you want to add more overloads, and another is that the first overload will only be called if there is an exact match to bool.

提交回复
热议问题