Lambda/Function help

I have a collection of objects, and I want to add a collision callback via lambda functions.

Basically, I want this to be able to happen:

 
object01.SetCollisionCallback([](Object*){/*...*/});


The interface will be always the same.

Is it possible, do you have any tips for this?
It's completely possible, I don't know what you're having a hard time with. Just take a std::function as an argument to SetCollisionCallback and you're good to go.
I was having some hard time just storing it.
Not completely into C++11 stuff yet, so didn't think about std::function.

Any way I could check if a function is assigned?

EDIT: Found out about the exception.
Last edited on
http://en.cppreference.com/w/cpp/utility/functional/function/operator_bool

Avoid use of exception handling whenever possible.
Last edited on
Avoid use of exception handling whenever possible.

Do you have a link to something describing a reason for this? I don't want to derail this thread so I'll just ask for a link.
I think LB's wording was a little weird.

He's saying this:

1
2
3
4
if(func)
    func();
else
    /* func not assigned */


is preferable to this:

1
2
3
4
try
    func();
catch(...)
    /* func not assigned */


The reason why should be fairly obvious.
@ Disch: OK, that makes sense. I think I just hop between too many threads at once and lose track of the conversation. LB means you should minimize the use of exception handling, i.e. don't use it to control regular program flow, and the bool operator overload for the std::function class is how you would do that in this case. There is no use in calling a function and having it throw a bad call failure when you can just test to see if it exists in the first place.

I wonder how that operator works by the way. If it only looks to see if the address not null or if it has some other mechanism to tell it that the variable has been initialized and\or if it is still valid.
I wonder how that operator works by the way. If it only looks to see if the address not null

You can look:

LLVM libc++ http://llvm.org/svn/llvm-project/libcxx/trunk/include/functional

1
2
3
    // function capacity:
    _LIBCPP_INLINE_VISIBILITY
        _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {return __f_;}


GNU libstdc++ http://gcc.gnu.org/viewcvs/gcc/trunk/libstdc%2B%2B-v3/include/std/functional?view=markup#l2347

1
2
3
4
5
6
 explicit operator bool() const noexcept
	      { return !_M_empty(); }

// ...

    bool _M_empty() const { return !_M_manager; }
Last edited on
@ Cubbi: Thanks! That is interesting to have bookmarked. I just need to find out where to download them from, my Google-Fu is failing me and I can't grep a website from Windows to find where some of these variables are being declared.
Topic archived. No new replies allowed.