tower120
tower120

Reputation: 5255

C++11 lambda function as callback and default value

I want to pass a lambda function to another function:

template<typename T>     
void test2(T fn){
    fn();
}

test2([]{cout<<"Hi"});

But I also want a default empty function in test2. So I do the next:

auto empty_lambda = []{};

template<typename T = decltype(empty_lambda)>
void test(T fn = empty_lambda){
    fn();
}

test();

And all good, but I can't put

auto empty_lambda = []{};

inside the class, so I have to keep it in global scope.

Can I improve this somehow? Except option with void test2(){ test2([]{}); }

Upvotes: 1

Views: 338

Answers (2)

Casey
Casey

Reputation: 42554

If it doesn't have to be a lambda, you could more portably use a plain-old static member function:

class foo {
    static void do_nothing() {}
public:
    template<typename T = decltype(do_nothing)>
    void test(T fn = do_nothing){
        fn();
    }
};

but if you really want lambda syntax, you can take advantage of the implicit conversion to function pointer:

class foo {
public:
    template<typename T = void(*)()>
    void test(T fn = []{}){
        fn();
    }
};

RETRACTION: Original answer is non-portable, the standard does not specify that any lambda closure has a literal type so as to be usable in a constant expression.

Believe it or not, you can use auto to declare a static data member (per C++11 §[dcl.spec.auto]/4):

class foo {
    static constexpr auto empty_lambda = []{};
public:
    template<typename T = decltype(empty_lambda)>
    void test(T fn = empty_lambda){
        fn();
    }
};

constexpr decltype(foo::empty_lambda) foo::empty_lambda;

The definition of the constexpr static data member is - to say the least - messy. (Live code at Coliru).

Upvotes: 1

P0W
P0W

Reputation: 47784

You can use std::function like following :

class X
{
   static std::function<void()> f;

   template<typename T = decltype(f)>
   void test(T fn = f){
       fn();
   }
};

std::function<void()> X::f = []{};

See HERE

Upvotes: 0

Related Questions