简体   繁体   中英

Simplifying the use of std::function stored within a class's std::vector member

I have written this basic class to store std::function<T> within std::vector<T> and I have two free function templates foo() and bar() that both return void and take a std::vector<T> as their parameter. Currently they do exactly the same for simplicity sakes; but let's say for future reference they will be doing different calculations or tasks. So far this is what I have come up with:

#include <vector>
#include <functional
#include <iostream>
#include <exception>

template<typename T>
class MyClass {
private:
    std::vector<std::function<void(std::vector<T>)>> myFuncs_;    
public:
    MyClass() = default;

    void addFunc( std::function<void(std::vector<T>)> func ) {
        myFuncs_.push_back(func);
    }

    std::function<void(std::vector<T>)> caller(unsigned idx) {
        return myFuncs_.at(idx);
    }
};

template<typename T>
void foo(std::vector<T> data) {
    std::cout << "foo() called:\n";

    for (auto& d : data) 
        std::cout << d << " ";
    std::cout << '\n';
}

template<typename T>
void bar(std::vector<T> data) {
    std::cout << "bar() called:\n";

    for (auto& d : data)
        std::cout << d << " ";
    std::cout << '\n';
} 

int main() {
    try {
        MyClass<int> myClass;
        std::vector<int> a{ 1,3,5,7,9 };
        std::vector<int> b{ 2,4,6,8,10 };

        std::function<void(std::vector<int>)> funcA = std::bind(foo<int>, a);
        std::function<void(std::vector<int>)> funcB = std::bind(bar<int>, b);
        myClass.addFunc( funcA );
        myClass.addFunc( funcB );

        myClass.caller(0)(a);
        myClass.caller(1)(b);       

    } catch( std::runtime_error& e ) {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;    
}  

And this sure enough outputs:

foo() called:
1 3 5 7 9
bar() called:
2 4 6 8 10

Here's what I would like to know: is there or are there any way(s) to simplify this code; some of the syntax looks redundant, for example: In the main function after I had instantiated an instance of my class template and created an std::vector with values, I then create an instance of std::function<T> using std::bind with the function I want to then add to my class's vector. Then after binding them and adding them to my class's container, this is where I call the class's function to index the function I want to call using std::functions 's operator() . However the function is expecting a std::vector<T> so it appears that I am passing this vector<T> multiple times as you can see from this part from my code above.

// std::vector<T> being passed to std::bind
std::function<void(std::vector<int>)> funcA = std::bind(foo<int>,a);
myClass.addFunc( funcA );
myClass.caller(0)(a);  // Again std::vector<T> being passed but to `std::function`'s operator because the stored function requires this parameter. 

Can this be simplified or is this just in the semantics of how std::function and std::bind work? If this can be simplified, would it be done within the class itself to make it easier on the user or would it be from the user side?

You're using std::bind the wrong way, eg in

std::function<void(std::vector<int>)> funcA = std::bind(foo<int>, a);

You've already bound the argument a to foo<int> which mean that whatever parameter you'll pass to funcA will not take effect, the above is equivalent to

std::function<void()> funcA = std::bind(foo<int>, a);

For the part of code simplicity, if you want to stick with std::bind you can just have a call operator on MyClass that call all the registered std::function :

template<typename T>
class MyClass {
private:
    std::vector<std::function<void()>> myFuncs_;
public:
    MyClass() = default;

    template <class... F, std::enable_if_t<(sizeof...(F) > 0), bool> = true>
    void addFunc(F&&... func) {
        ((myFuncs_.push_back(std::forward<F>(func))), ...);
    }

    void operator()() const {
        for (auto& fn : myFuncs_) {
            fn();
        }
    }
};


auto funcA = std::bind(foo<int>, a);
auto funcB = std::bind(bar<int>, b);
myClass.addFunc(funcA, funcB);
myClass();

using this same idea you can at any time switch to lambdas instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM