Is storing any type of function in one variable possible?What are the differences between a pointer variable and a reference variable in C++?What's the difference between a method and a function?What is the naming convention in Python for variable and function names?var functionName = function() vs function functionName() What is the scope of variables in JavaScript?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionHow to determine if variable is 'undefined' or 'null'?How to check if a variable is set in Bash?JavaScript check if variable exists (is defined/initialized)

Examples of smooth manifolds admitting inbetween one and a continuum of complex structures

What historical events would have to change in order to make 19th century "steampunk" technology possible?

How much of data wrangling is a data scientist's job?

What does the expression "A Mann!" means

What type of content (depth/breadth) is expected for a short presentation for Asst Professor interview in the UK?

How to properly check if the given string is empty in a POSIX shell script?

Is finding a path with more red vertices than blue vertices NP-hard?

Question about the derivation of the intensity formula of a diffraction grating

Expand and Contract

Processor speed limited at 0.4 GHz

pgfplots: How to draw exponential graph with 60° start angle?

Different meanings of こわい

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

Rotate ASCII Art by 45 Degrees

What does “the session was packed” mean in this context?

Does the Idaho Potato Commission associate potato skins with healthy eating?

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

Why didn't Boeing produce its own regional jet?

Mathematica command that allows it to read my intentions

What about the virus in The Twelve Monkeys?

How do I deal with an unproductive colleague in a small company?

How does an LSTM process sequences longer than its memory?

How dangerous is XSS?

What reasons are there for a Capitalist to oppose a 100% inheritance tax?



Is storing any type of function in one variable possible?


What are the differences between a pointer variable and a reference variable in C++?What's the difference between a method and a function?What is the naming convention in Python for variable and function names?var functionName = function() vs function functionName() What is the scope of variables in JavaScript?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionHow to determine if variable is 'undefined' or 'null'?How to check if a variable is set in Bash?JavaScript check if variable exists (is defined/initialized)













11















I'm trying to make a menu array where each element is a struct that stores variables for text, key that needs to be pressed to select that item and function called on that key press (something like "Quit", 'Q', Quit()). I thought this would make things more efficient, but I can't find a way to make it work with varied function and parameter types (for example one item should be able to call a void function with no parameters, another a class int function with two parameters and so on). Is there a good way to do this or am I better off giving up on the idea?



Edit: Thank you all for your advice! The proposed solutions feel a little too complex for my newbie self, but attempting to understand them gave me some ideas! I ended up making the third variable hold an enum instead of a direct function call and then created a switch function that calls other functions based on that value.










share|improve this question



















  • 2





    You can use a lambda expression that calls your actual function

    – Liran Funaro
    Mar 19 at 9:55






  • 1





    Where do the class instance and the two parameters come from?

    – Bergi
    Mar 19 at 13:54






  • 3





    Look up the Command pattern. Note that I’m not saying not to use a function for this. But this pattern is the generalised form of what you need.

    – Konrad Rudolph
    Mar 19 at 14:32











  • Note that a interface with a single method is roughly equivalent to a std::function type.

    – Caleth
    Mar 19 at 14:55















11















I'm trying to make a menu array where each element is a struct that stores variables for text, key that needs to be pressed to select that item and function called on that key press (something like "Quit", 'Q', Quit()). I thought this would make things more efficient, but I can't find a way to make it work with varied function and parameter types (for example one item should be able to call a void function with no parameters, another a class int function with two parameters and so on). Is there a good way to do this or am I better off giving up on the idea?



Edit: Thank you all for your advice! The proposed solutions feel a little too complex for my newbie self, but attempting to understand them gave me some ideas! I ended up making the third variable hold an enum instead of a direct function call and then created a switch function that calls other functions based on that value.










share|improve this question



















  • 2





    You can use a lambda expression that calls your actual function

    – Liran Funaro
    Mar 19 at 9:55






  • 1





    Where do the class instance and the two parameters come from?

    – Bergi
    Mar 19 at 13:54






  • 3





    Look up the Command pattern. Note that I’m not saying not to use a function for this. But this pattern is the generalised form of what you need.

    – Konrad Rudolph
    Mar 19 at 14:32











  • Note that a interface with a single method is roughly equivalent to a std::function type.

    – Caleth
    Mar 19 at 14:55













11












11








11








I'm trying to make a menu array where each element is a struct that stores variables for text, key that needs to be pressed to select that item and function called on that key press (something like "Quit", 'Q', Quit()). I thought this would make things more efficient, but I can't find a way to make it work with varied function and parameter types (for example one item should be able to call a void function with no parameters, another a class int function with two parameters and so on). Is there a good way to do this or am I better off giving up on the idea?



Edit: Thank you all for your advice! The proposed solutions feel a little too complex for my newbie self, but attempting to understand them gave me some ideas! I ended up making the third variable hold an enum instead of a direct function call and then created a switch function that calls other functions based on that value.










share|improve this question
















I'm trying to make a menu array where each element is a struct that stores variables for text, key that needs to be pressed to select that item and function called on that key press (something like "Quit", 'Q', Quit()). I thought this would make things more efficient, but I can't find a way to make it work with varied function and parameter types (for example one item should be able to call a void function with no parameters, another a class int function with two parameters and so on). Is there a good way to do this or am I better off giving up on the idea?



Edit: Thank you all for your advice! The proposed solutions feel a little too complex for my newbie self, but attempting to understand them gave me some ideas! I ended up making the third variable hold an enum instead of a direct function call and then created a switch function that calls other functions based on that value.







c++ function variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 19 at 20:03







Rhyme

















asked Mar 19 at 9:51









RhymeRhyme

565




565







  • 2





    You can use a lambda expression that calls your actual function

    – Liran Funaro
    Mar 19 at 9:55






  • 1





    Where do the class instance and the two parameters come from?

    – Bergi
    Mar 19 at 13:54






  • 3





    Look up the Command pattern. Note that I’m not saying not to use a function for this. But this pattern is the generalised form of what you need.

    – Konrad Rudolph
    Mar 19 at 14:32











  • Note that a interface with a single method is roughly equivalent to a std::function type.

    – Caleth
    Mar 19 at 14:55












  • 2





    You can use a lambda expression that calls your actual function

    – Liran Funaro
    Mar 19 at 9:55






  • 1





    Where do the class instance and the two parameters come from?

    – Bergi
    Mar 19 at 13:54






  • 3





    Look up the Command pattern. Note that I’m not saying not to use a function for this. But this pattern is the generalised form of what you need.

    – Konrad Rudolph
    Mar 19 at 14:32











  • Note that a interface with a single method is roughly equivalent to a std::function type.

    – Caleth
    Mar 19 at 14:55







2




2





You can use a lambda expression that calls your actual function

– Liran Funaro
Mar 19 at 9:55





You can use a lambda expression that calls your actual function

– Liran Funaro
Mar 19 at 9:55




1




1





Where do the class instance and the two parameters come from?

– Bergi
Mar 19 at 13:54





Where do the class instance and the two parameters come from?

– Bergi
Mar 19 at 13:54




3




3





Look up the Command pattern. Note that I’m not saying not to use a function for this. But this pattern is the generalised form of what you need.

– Konrad Rudolph
Mar 19 at 14:32





Look up the Command pattern. Note that I’m not saying not to use a function for this. But this pattern is the generalised form of what you need.

– Konrad Rudolph
Mar 19 at 14:32













Note that a interface with a single method is roughly equivalent to a std::function type.

– Caleth
Mar 19 at 14:55





Note that a interface with a single method is roughly equivalent to a std::function type.

– Caleth
Mar 19 at 14:55












2 Answers
2






active

oldest

votes


















9














There are actually a few ways of doing this.



One way is to use std::bind to bind all functions to void func(void) then you can store them equally.

The other way is to create a generic function/lambda which will call your function.

To store your functions you can use std::function.



Also consider overriding operator() of your classes.






share|improve this answer






























    1














    The classic way of handling this is to have all the functions take the same parameters, and for those to be very flexible. For example, an integer or enum, and a pointer.



    • your no-parameter function is passed -1 and nullptr and ignores them

    • your multi-parameter function casts the pointer to a pointer to some struct or class that holds all the bits and pieces it needs (and of course your calling code made that instance and passed its address)

    The reason an enum or integer is hoisted out as one of the parameters is that "command type" is a super popular thing to need, so why do all that casting and extracting to get it?



    If you have a performance problem as a result of this approach, then there are others, but this has literally been used for decades in Windows.






    share|improve this answer























      Your Answer






      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: "1"
      ;
      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: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      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%2fstackoverflow.com%2fquestions%2f55238001%2fis-storing-any-type-of-function-in-one-variable-possible%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      9














      There are actually a few ways of doing this.



      One way is to use std::bind to bind all functions to void func(void) then you can store them equally.

      The other way is to create a generic function/lambda which will call your function.

      To store your functions you can use std::function.



      Also consider overriding operator() of your classes.






      share|improve this answer



























        9














        There are actually a few ways of doing this.



        One way is to use std::bind to bind all functions to void func(void) then you can store them equally.

        The other way is to create a generic function/lambda which will call your function.

        To store your functions you can use std::function.



        Also consider overriding operator() of your classes.






        share|improve this answer

























          9












          9








          9







          There are actually a few ways of doing this.



          One way is to use std::bind to bind all functions to void func(void) then you can store them equally.

          The other way is to create a generic function/lambda which will call your function.

          To store your functions you can use std::function.



          Also consider overriding operator() of your classes.






          share|improve this answer













          There are actually a few ways of doing this.



          One way is to use std::bind to bind all functions to void func(void) then you can store them equally.

          The other way is to create a generic function/lambda which will call your function.

          To store your functions you can use std::function.



          Also consider overriding operator() of your classes.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 19 at 9:58









          Petar VelevPetar Velev

          1,748719




          1,748719























              1














              The classic way of handling this is to have all the functions take the same parameters, and for those to be very flexible. For example, an integer or enum, and a pointer.



              • your no-parameter function is passed -1 and nullptr and ignores them

              • your multi-parameter function casts the pointer to a pointer to some struct or class that holds all the bits and pieces it needs (and of course your calling code made that instance and passed its address)

              The reason an enum or integer is hoisted out as one of the parameters is that "command type" is a super popular thing to need, so why do all that casting and extracting to get it?



              If you have a performance problem as a result of this approach, then there are others, but this has literally been used for decades in Windows.






              share|improve this answer



























                1














                The classic way of handling this is to have all the functions take the same parameters, and for those to be very flexible. For example, an integer or enum, and a pointer.



                • your no-parameter function is passed -1 and nullptr and ignores them

                • your multi-parameter function casts the pointer to a pointer to some struct or class that holds all the bits and pieces it needs (and of course your calling code made that instance and passed its address)

                The reason an enum or integer is hoisted out as one of the parameters is that "command type" is a super popular thing to need, so why do all that casting and extracting to get it?



                If you have a performance problem as a result of this approach, then there are others, but this has literally been used for decades in Windows.






                share|improve this answer

























                  1












                  1








                  1







                  The classic way of handling this is to have all the functions take the same parameters, and for those to be very flexible. For example, an integer or enum, and a pointer.



                  • your no-parameter function is passed -1 and nullptr and ignores them

                  • your multi-parameter function casts the pointer to a pointer to some struct or class that holds all the bits and pieces it needs (and of course your calling code made that instance and passed its address)

                  The reason an enum or integer is hoisted out as one of the parameters is that "command type" is a super popular thing to need, so why do all that casting and extracting to get it?



                  If you have a performance problem as a result of this approach, then there are others, but this has literally been used for decades in Windows.






                  share|improve this answer













                  The classic way of handling this is to have all the functions take the same parameters, and for those to be very flexible. For example, an integer or enum, and a pointer.



                  • your no-parameter function is passed -1 and nullptr and ignores them

                  • your multi-parameter function casts the pointer to a pointer to some struct or class that holds all the bits and pieces it needs (and of course your calling code made that instance and passed its address)

                  The reason an enum or integer is hoisted out as one of the parameters is that "command type" is a super popular thing to need, so why do all that casting and extracting to get it?



                  If you have a performance problem as a result of this approach, then there are others, but this has literally been used for decades in Windows.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 19 at 14:35









                  Kate GregoryKate Gregory

                  17.5k74881




                  17.5k74881



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • 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%2fstackoverflow.com%2fquestions%2f55238001%2fis-storing-any-type-of-function-in-one-variable-possible%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

                      Masuk log Menu navigasi

                      Identifying “long and narrow” polygons in with PostGISlength and width of polygonWhy postgis st_overlaps reports Qgis' “avoid intersections” generated polygon as overlapping with others?Adjusting polygons to boundary and filling holesDrawing polygons with fixed area?How to remove spikes in Polygons with PostGISDeleting sliver polygons after difference operation in QGIS?Snapping boundaries in PostGISSplit polygon into parts adding attributes based on underlying polygon in QGISSplitting overlap between polygons and assign to nearest polygon using PostGIS?Expanding polygons and clipping at midpoint?Removing Intersection of Buffers in Same Layers

                      Старые Смолеговицы Содержание История | География | Демография | Достопримечательности | Примечания | НавигацияHGЯOLHGЯOL41 206 832 01641 606 406 141Административно-территориальное деление Ленинградской области«Переписная оброчная книга Водской пятины 1500 года», С. 793«Карта Ингерманландии: Ивангорода, Яма, Копорья, Нотеборга», по материалам 1676 г.«Генеральная карта провинции Ингерманландии» Э. Белинга и А. Андерсина, 1704 г., составлена по материалам 1678 г.«Географический чертёж над Ижорскою землей со своими городами» Адриана Шонбека 1705 г.Новая и достоверная всей Ингерманландии ланткарта. Грав. А. Ростовцев. СПб., 1727 г.Топографическая карта Санкт-Петербургской губернии. 5-и верстка. Шуберт. 1834 г.Описание Санкт-Петербургской губернии по уездам и станамСпецкарта западной части России Ф. Ф. Шуберта. 1844 г.Алфавитный список селений по уездам и станам С.-Петербургской губернииСписки населённых мест Российской Империи, составленные и издаваемые центральным статистическим комитетом министерства внутренних дел. XXXVII. Санкт-Петербургская губерния. По состоянию на 1862 год. СПб. 1864. С. 203Материалы по статистике народного хозяйства в С.-Петербургской губернии. Вып. IX. Частновладельческое хозяйство в Ямбургском уезде. СПб, 1888, С. 146, С. 2, 7, 54Положение о гербе муниципального образования Курское сельское поселениеСправочник истории административно-территориального деления Ленинградской области.Топографическая карта Ленинградской области, квадрат О-35-23-В (Хотыницы), 1930 г.АрхивированоАдминистративно-территориальное деление Ленинградской области. — Л., 1933, С. 27, 198АрхивированоАдминистративно-экономический справочник по Ленинградской области. — Л., 1936, с. 219АрхивированоАдминистративно-территориальное деление Ленинградской области. — Л., 1966, с. 175АрхивированоАдминистративно-территориальное деление Ленинградской области. — Лениздат, 1973, С. 180АрхивированоАдминистративно-территориальное деление Ленинградской области. — Лениздат, 1990, ISBN 5-289-00612-5, С. 38АрхивированоАдминистративно-территориальное деление Ленинградской области. — СПб., 2007, с. 60АрхивированоКоряков Юрий База данных «Этно-языковой состав населённых пунктов России». Ленинградская область.Административно-территориальное деление Ленинградской области. — СПб, 1997, ISBN 5-86153-055-6, С. 41АрхивированоКультовый комплекс Старые Смолеговицы // Электронная энциклопедия ЭрмитажаПроблемы выявления, изучения и сохранения культовых комплексов с каменными крестами: по материалам работ 2016-2017 гг. в Ленинградской области