Seokmin Hong Seokmin Hong - 1 year ago 69
C++ Question

How Can I use Null Lambda in C++?

I want to declare a function like this:

template <typename Lambda>
int foo(Lambda bar) {
if(/* check bar is null lambda */)
return -1;
else
bar(3);
}

int main() {
std::cout << foo([](int a)->int{return a + 3;}) << std::endl;
std::cout << foo(NULL_LAMBDA) << std::endl;
}


Then, how can I declare the
NULL_LAMBDA
and the condition checking passed lambda function whether is null?

VTT VTT
Answer Source

You can add a dedicated specialization:

#include <iostream>
#include <type_traits>
#include <cstddef>

template<typename Lambda> int
foo(Lambda bar)
{
    return(bar(3));
}

template<> int
foo<::std::nullptr_t>(::std::nullptr_t)
{
    return(-1);
}

int main()
{
    ::std::cout << foo([] (int a) -> int {return(a + 3);}) << ::std::endl;
    ::std::cout << foo(nullptr) << ::std::endl;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download