Simplifying the use of std::function stored in an std::vector within a class












0














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?









share



























    0














    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?









    share

























      0












      0








      0







      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?









      share













      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?







      c++ template c++17





      share












      share










      share



      share










      asked 4 mins ago









      Francis Cugler

      25116




      25116



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210548%2fsimplifying-the-use-of-stdfunction-stored-in-an-stdvector-within-a-class%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210548%2fsimplifying-the-use-of-stdfunction-stored-in-an-stdvector-within-a-class%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Costa Masnaga

          Fotorealismo

          Sidney Franklin