Default lambda as templated parameter of a function

后端 未结 5 582
悲&欢浪女
悲&欢浪女 2021-01-22 02:07

Consider the following code

template void foo(const T& t = []() {}) {
  // implementation here
}

void bar() {
  foo([&         


        
5条回答
  •  日久生厌
    2021-01-22 02:09

    Another (very efficient) way - default T to be a null functor.

    // no_op is a function object which does nothing, regardless of how many
    // arguments you give it. It will be elided completely unless you compile with
    // -O0
    struct no_op 
    { 
        template
        constexpr void operator()(Args&&...) const {} 
    };
    
    // foo defaults to using a default-constructed no_op as its function object
    template void foo(T&& t = T()) 
    {    
      // implementation here
        t();
    }
    
    void bar() {
      foo([&](){ std::cout << "something\n"; }); // this compiles
      foo(); // this now compiles
    }
    

提交回复
热议问题