C++11 variadic std::function parameter

前端 未结 4 1103
无人共我
无人共我 2020-12-14 02:41

A function named test takes std::function<> as its parameter.

template
void test(std::functio         


        
4条回答
  •  太阳男子
    2020-12-14 03:08

    This is an old one, and I can't seem to find much on the same topic, so I thought I would go ahead and put in a note.

    Compiled on GCC 4.8.2, the following works:

    template
    R test(const std::function& func)
    {
        // ...
    }
    

    However, you can't just call it by passing in your pointers, lambdas, etc. However, the following 2 examples both work with it:

    test(std::function(
            [](int i, float f, std::string s)
            {
                std::cout << i << " " << f << " " << s << std::endl;
            }));
    

    Also:

    void test2(int i, float f, std::string s)
    {
        std::cout << i << " " << f << " " << s << std::endl;
    }
    
    // In a function somewhere:
    test(std::function(&test2));
    

    The downside of these should stand out pretty obviously: you have to explicitly declare the std::function for them, which might look a little bit ugly.

    That said, though, I threw that together with a tuple that gets expanded to call the incoming function, and it works, just requiring a little bit more of an explicitly saying what you're doing calling the test function.

    Example code including the tuple thing, if you want to play with it: http://ideone.com/33mqZA

提交回复
热议问题