Default argument for a functor in a templated parameterWhat are C++ functors and their uses?Why can templates only be implemented in the header file?Function passed as template argumentLambda expressions as class template parametersType-only template argument to lambdaIs there a way to detect at compile time whether a generic lambda can be successfully invoked with a given set of parameter types?Template deduction for default template argumentCan I generate a function without providing arguments?

Label "Alto en grasa saturada, sal, ..." should there also be Alta?

Mute single speaker?

Bidirectional Dictionary

How many people can lift Thor's hammer?

If one can diff from Vim without the need to boot `vimdiff` then why is it a binary program?

MOSFET broke after attaching capacitor bank

Professor refuses to write a recommendation letter to students who haven't written a research paper with him

What would a biological creature need in order to see into the future?

Is every coset of a group closed under taking inverses?

If magnetic force can't do any work, then how can we define a potential?

Would you recommend a keyboard for beginners with or without lights in keys for learning?

Dissuading my girlfriend from a scam

What's this constructed number's starter?

How could a planet have one hemisphere way warmer than the other without the planet being tidally locked?

Life post thesis submission is terrifying - Help!

How do I make my fill-in-the-blank exercise more obvious?

'Hard work never hurt anyone' Why not 'hurts'?

Is there any difference between these two sentences? (Adverbs)

Why does the UK Prime Minister need the permission of Parliament to call a general election?

What drugs were used in England during the High Middle Ages?

Do 643,000 Americans go bankrupt every year due to medical bills?

How do I anonymously report the Establishment Clause being broken?

Comparing elements in a nested list to generate a new list

Is a paralyzed creature limp or rigid?



Default argument for a functor in a templated parameter


What are C++ functors and their uses?Why can templates only be implemented in the header file?Function passed as template argumentLambda expressions as class template parametersType-only template argument to lambdaIs there a way to detect at compile time whether a generic lambda can be successfully invoked with a given set of parameter types?Template deduction for default template argumentCan I generate a function without providing arguments?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















I would like to have a default lambda for a functor argument in my function.



I am aware it is possible using a struct and operator() like this:



struct AddOne 
int operator()(int a)
return a+1;

;

template <typename Functor = AddOne>
int run_old(int x, Functor func = AddOne())

return func(x);



But I was wondering if there was a modern way, given the changes in the standard in either c++14/17/20, to make this work?



template <typename Functor>
int run_new(int x, Functor func = [](int a) return a+1; )

return func(x);



I'm not sure what one would use as the default type to Functor, or if there is syntax i'm unaware of.



https://godbolt.org/z/Hs6vQs










share|improve this question


























  • "modern way" What's wrong with the old way? The struct method is much easier to read at the function site.

    – Nicol Bolas
    9 hours ago






  • 2





    In the old way, you likely don't want to provide both default template and function arguments this way: wandbox.org/permlink/PtSwiQwsNDyDrshu. Use Functor func = Functor() instead.

    – Daniel Langr
    9 hours ago


















6















I would like to have a default lambda for a functor argument in my function.



I am aware it is possible using a struct and operator() like this:



struct AddOne 
int operator()(int a)
return a+1;

;

template <typename Functor = AddOne>
int run_old(int x, Functor func = AddOne())

return func(x);



But I was wondering if there was a modern way, given the changes in the standard in either c++14/17/20, to make this work?



template <typename Functor>
int run_new(int x, Functor func = [](int a) return a+1; )

return func(x);



I'm not sure what one would use as the default type to Functor, or if there is syntax i'm unaware of.



https://godbolt.org/z/Hs6vQs










share|improve this question


























  • "modern way" What's wrong with the old way? The struct method is much easier to read at the function site.

    – Nicol Bolas
    9 hours ago






  • 2





    In the old way, you likely don't want to provide both default template and function arguments this way: wandbox.org/permlink/PtSwiQwsNDyDrshu. Use Functor func = Functor() instead.

    – Daniel Langr
    9 hours ago














6












6








6


2






I would like to have a default lambda for a functor argument in my function.



I am aware it is possible using a struct and operator() like this:



struct AddOne 
int operator()(int a)
return a+1;

;

template <typename Functor = AddOne>
int run_old(int x, Functor func = AddOne())

return func(x);



But I was wondering if there was a modern way, given the changes in the standard in either c++14/17/20, to make this work?



template <typename Functor>
int run_new(int x, Functor func = [](int a) return a+1; )

return func(x);



I'm not sure what one would use as the default type to Functor, or if there is syntax i'm unaware of.



https://godbolt.org/z/Hs6vQs










share|improve this question
















I would like to have a default lambda for a functor argument in my function.



I am aware it is possible using a struct and operator() like this:



struct AddOne 
int operator()(int a)
return a+1;

;

template <typename Functor = AddOne>
int run_old(int x, Functor func = AddOne())

return func(x);



But I was wondering if there was a modern way, given the changes in the standard in either c++14/17/20, to make this work?



template <typename Functor>
int run_new(int x, Functor func = [](int a) return a+1; )

return func(x);



I'm not sure what one would use as the default type to Functor, or if there is syntax i'm unaware of.



https://godbolt.org/z/Hs6vQs







c++ lambda c++14 c++17 template-deduction






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 9 hours ago









max66

45.4k7 gold badges48 silver badges80 bronze badges




45.4k7 gold badges48 silver badges80 bronze badges










asked 9 hours ago









SalgarSalgar

6,3711 gold badge22 silver badges36 bronze badges




6,3711 gold badge22 silver badges36 bronze badges















  • "modern way" What's wrong with the old way? The struct method is much easier to read at the function site.

    – Nicol Bolas
    9 hours ago






  • 2





    In the old way, you likely don't want to provide both default template and function arguments this way: wandbox.org/permlink/PtSwiQwsNDyDrshu. Use Functor func = Functor() instead.

    – Daniel Langr
    9 hours ago


















  • "modern way" What's wrong with the old way? The struct method is much easier to read at the function site.

    – Nicol Bolas
    9 hours ago






  • 2





    In the old way, you likely don't want to provide both default template and function arguments this way: wandbox.org/permlink/PtSwiQwsNDyDrshu. Use Functor func = Functor() instead.

    – Daniel Langr
    9 hours ago

















"modern way" What's wrong with the old way? The struct method is much easier to read at the function site.

– Nicol Bolas
9 hours ago





"modern way" What's wrong with the old way? The struct method is much easier to read at the function site.

– Nicol Bolas
9 hours ago




2




2





In the old way, you likely don't want to provide both default template and function arguments this way: wandbox.org/permlink/PtSwiQwsNDyDrshu. Use Functor func = Functor() instead.

– Daniel Langr
9 hours ago






In the old way, you likely don't want to provide both default template and function arguments this way: wandbox.org/permlink/PtSwiQwsNDyDrshu. Use Functor func = Functor() instead.

– Daniel Langr
9 hours ago













6 Answers
6






active

oldest

votes


















8
















From C++11 you can already do that:



template <typename Functor = int(int)>
int run_new(int x, Functor func = [](int a) return a+1; )

return func(x);






share|improve this answer

























  • works only with non-capturing lambda, no? (not relevant for the question as asked)

    – formerlyknownas_463035818
    9 hours ago






  • 1





    @formerlyknownas_463035818: If you pass a capturing lambda, then the template function will deduce the type of this lambda, thus overriding the default type of int(int).

    – Nicol Bolas
    9 hours ago







  • 3





    @formerlyknownas_463035818 I don't think you can capture anything in this context since the lambda is used as a default argument.

    – Biagio Festa
    9 hours ago






  • 1





    @formerlyknownas_463035818 You couldn't capture a global anyway. Capturing requires automatic storage.

    – Biagio Festa
    9 hours ago






  • 2





    Note that GCC and Clang are smart enough to inline the lambda call even though it gets converted into a function pointer. godbolt.org/z/nl4qEj

    – Brian
    9 hours ago



















3
















Just add an overload for this.



template <typename Functor>
int run_new(int x, Functor func)

return func(x);


int run_new(int x)

return run_new(x, [](int a) return a+1; );



Allows you to get around not beening able to have a lambda expression as a default function argument.






share|improve this answer


































    1
















    Not quite "modern" but you could use plain old overloading with a non-template method taking only a single parameter:



    int run_new(int x) 

    return func(x,[](int a) return a+1;); // calls the template overload






    share|improve this answer
































      1
















      Just for fun, in C++20 we have both (1) lambdas in unevaluated contexts and (2) lambdas without capture are default constructible. Combine those two and you get:



      template <typename Functor = decltype([](int a) return a+1; )>
      int run_new(int x, Functor func = )

      return func(x);



      Obligatory godbolt.






      share|improve this answer
































        0
















        Alternatively to other questions, you can even avoid templates:



        int run_new(int x, std::function<int(int)> func = [](int a) return a + 1; )

        return func(x);






        share|improve this answer






















        • 5





          Do note that you do incur a cost for this. std::function uses type erasure so you have dynamic allocation and more than likely lose the ability to inline the code.

          – NathanOliver
          9 hours ago






        • 2





          @NathanOliver Both GCC and Clang seem to be smart enough to generate the same inlined assembly code for f, which is minimal: godbolt.org/z/uuEeNE. Need to admit I was surprised.

          – Daniel Langr
          9 hours ago







        • 3





          @DanielLangr But now the functor has to be copyable

          – Artyer
          9 hours ago











        • @Artyer That's the drawback. The advantage is that you don't need to expose the function definition in a header file.

          – Daniel Langr
          9 hours ago



















        0
















        The best I can imagine pass through a variable



        static constexpr auto defFunc = [](int a) return a+1; ;

        template <typename Functor = decltype(defFunc)>
        int run_new(int x, Functor func = defFunc)

        return func(x);






        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%2f57791248%2fdefault-argument-for-a-functor-in-a-templated-parameter%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8
















          From C++11 you can already do that:



          template <typename Functor = int(int)>
          int run_new(int x, Functor func = [](int a) return a+1; )

          return func(x);






          share|improve this answer

























          • works only with non-capturing lambda, no? (not relevant for the question as asked)

            – formerlyknownas_463035818
            9 hours ago






          • 1





            @formerlyknownas_463035818: If you pass a capturing lambda, then the template function will deduce the type of this lambda, thus overriding the default type of int(int).

            – Nicol Bolas
            9 hours ago







          • 3





            @formerlyknownas_463035818 I don't think you can capture anything in this context since the lambda is used as a default argument.

            – Biagio Festa
            9 hours ago






          • 1





            @formerlyknownas_463035818 You couldn't capture a global anyway. Capturing requires automatic storage.

            – Biagio Festa
            9 hours ago






          • 2





            Note that GCC and Clang are smart enough to inline the lambda call even though it gets converted into a function pointer. godbolt.org/z/nl4qEj

            – Brian
            9 hours ago
















          8
















          From C++11 you can already do that:



          template <typename Functor = int(int)>
          int run_new(int x, Functor func = [](int a) return a+1; )

          return func(x);






          share|improve this answer

























          • works only with non-capturing lambda, no? (not relevant for the question as asked)

            – formerlyknownas_463035818
            9 hours ago






          • 1





            @formerlyknownas_463035818: If you pass a capturing lambda, then the template function will deduce the type of this lambda, thus overriding the default type of int(int).

            – Nicol Bolas
            9 hours ago







          • 3





            @formerlyknownas_463035818 I don't think you can capture anything in this context since the lambda is used as a default argument.

            – Biagio Festa
            9 hours ago






          • 1





            @formerlyknownas_463035818 You couldn't capture a global anyway. Capturing requires automatic storage.

            – Biagio Festa
            9 hours ago






          • 2





            Note that GCC and Clang are smart enough to inline the lambda call even though it gets converted into a function pointer. godbolt.org/z/nl4qEj

            – Brian
            9 hours ago














          8














          8










          8









          From C++11 you can already do that:



          template <typename Functor = int(int)>
          int run_new(int x, Functor func = [](int a) return a+1; )

          return func(x);






          share|improve this answer













          From C++11 you can already do that:



          template <typename Functor = int(int)>
          int run_new(int x, Functor func = [](int a) return a+1; )

          return func(x);







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 9 hours ago









          Biagio FestaBiagio Festa

          6,4672 gold badges14 silver badges42 bronze badges




          6,4672 gold badges14 silver badges42 bronze badges















          • works only with non-capturing lambda, no? (not relevant for the question as asked)

            – formerlyknownas_463035818
            9 hours ago






          • 1





            @formerlyknownas_463035818: If you pass a capturing lambda, then the template function will deduce the type of this lambda, thus overriding the default type of int(int).

            – Nicol Bolas
            9 hours ago







          • 3





            @formerlyknownas_463035818 I don't think you can capture anything in this context since the lambda is used as a default argument.

            – Biagio Festa
            9 hours ago






          • 1





            @formerlyknownas_463035818 You couldn't capture a global anyway. Capturing requires automatic storage.

            – Biagio Festa
            9 hours ago






          • 2





            Note that GCC and Clang are smart enough to inline the lambda call even though it gets converted into a function pointer. godbolt.org/z/nl4qEj

            – Brian
            9 hours ago


















          • works only with non-capturing lambda, no? (not relevant for the question as asked)

            – formerlyknownas_463035818
            9 hours ago






          • 1





            @formerlyknownas_463035818: If you pass a capturing lambda, then the template function will deduce the type of this lambda, thus overriding the default type of int(int).

            – Nicol Bolas
            9 hours ago







          • 3





            @formerlyknownas_463035818 I don't think you can capture anything in this context since the lambda is used as a default argument.

            – Biagio Festa
            9 hours ago






          • 1





            @formerlyknownas_463035818 You couldn't capture a global anyway. Capturing requires automatic storage.

            – Biagio Festa
            9 hours ago






          • 2





            Note that GCC and Clang are smart enough to inline the lambda call even though it gets converted into a function pointer. godbolt.org/z/nl4qEj

            – Brian
            9 hours ago

















          works only with non-capturing lambda, no? (not relevant for the question as asked)

          – formerlyknownas_463035818
          9 hours ago





          works only with non-capturing lambda, no? (not relevant for the question as asked)

          – formerlyknownas_463035818
          9 hours ago




          1




          1





          @formerlyknownas_463035818: If you pass a capturing lambda, then the template function will deduce the type of this lambda, thus overriding the default type of int(int).

          – Nicol Bolas
          9 hours ago






          @formerlyknownas_463035818: If you pass a capturing lambda, then the template function will deduce the type of this lambda, thus overriding the default type of int(int).

          – Nicol Bolas
          9 hours ago





          3




          3





          @formerlyknownas_463035818 I don't think you can capture anything in this context since the lambda is used as a default argument.

          – Biagio Festa
          9 hours ago





          @formerlyknownas_463035818 I don't think you can capture anything in this context since the lambda is used as a default argument.

          – Biagio Festa
          9 hours ago




          1




          1





          @formerlyknownas_463035818 You couldn't capture a global anyway. Capturing requires automatic storage.

          – Biagio Festa
          9 hours ago





          @formerlyknownas_463035818 You couldn't capture a global anyway. Capturing requires automatic storage.

          – Biagio Festa
          9 hours ago




          2




          2





          Note that GCC and Clang are smart enough to inline the lambda call even though it gets converted into a function pointer. godbolt.org/z/nl4qEj

          – Brian
          9 hours ago






          Note that GCC and Clang are smart enough to inline the lambda call even though it gets converted into a function pointer. godbolt.org/z/nl4qEj

          – Brian
          9 hours ago














          3
















          Just add an overload for this.



          template <typename Functor>
          int run_new(int x, Functor func)

          return func(x);


          int run_new(int x)

          return run_new(x, [](int a) return a+1; );



          Allows you to get around not beening able to have a lambda expression as a default function argument.






          share|improve this answer































            3
















            Just add an overload for this.



            template <typename Functor>
            int run_new(int x, Functor func)

            return func(x);


            int run_new(int x)

            return run_new(x, [](int a) return a+1; );



            Allows you to get around not beening able to have a lambda expression as a default function argument.






            share|improve this answer





























              3














              3










              3









              Just add an overload for this.



              template <typename Functor>
              int run_new(int x, Functor func)

              return func(x);


              int run_new(int x)

              return run_new(x, [](int a) return a+1; );



              Allows you to get around not beening able to have a lambda expression as a default function argument.






              share|improve this answer















              Just add an overload for this.



              template <typename Functor>
              int run_new(int x, Functor func)

              return func(x);


              int run_new(int x)

              return run_new(x, [](int a) return a+1; );



              Allows you to get around not beening able to have a lambda expression as a default function argument.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 9 hours ago

























              answered 9 hours ago









              NathanOliverNathanOliver

              114k19 gold badges181 silver badges260 bronze badges




              114k19 gold badges181 silver badges260 bronze badges
























                  1
















                  Not quite "modern" but you could use plain old overloading with a non-template method taking only a single parameter:



                  int run_new(int x) 

                  return func(x,[](int a) return a+1;); // calls the template overload






                  share|improve this answer





























                    1
















                    Not quite "modern" but you could use plain old overloading with a non-template method taking only a single parameter:



                    int run_new(int x) 

                    return func(x,[](int a) return a+1;); // calls the template overload






                    share|improve this answer



























                      1














                      1










                      1









                      Not quite "modern" but you could use plain old overloading with a non-template method taking only a single parameter:



                      int run_new(int x) 

                      return func(x,[](int a) return a+1;); // calls the template overload






                      share|improve this answer













                      Not quite "modern" but you could use plain old overloading with a non-template method taking only a single parameter:



                      int run_new(int x) 

                      return func(x,[](int a) return a+1;); // calls the template overload







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 9 hours ago









                      formerlyknownas_463035818formerlyknownas_463035818

                      24.2k4 gold badges32 silver badges81 bronze badges




                      24.2k4 gold badges32 silver badges81 bronze badges
























                          1
















                          Just for fun, in C++20 we have both (1) lambdas in unevaluated contexts and (2) lambdas without capture are default constructible. Combine those two and you get:



                          template <typename Functor = decltype([](int a) return a+1; )>
                          int run_new(int x, Functor func = )

                          return func(x);



                          Obligatory godbolt.






                          share|improve this answer





























                            1
















                            Just for fun, in C++20 we have both (1) lambdas in unevaluated contexts and (2) lambdas without capture are default constructible. Combine those two and you get:



                            template <typename Functor = decltype([](int a) return a+1; )>
                            int run_new(int x, Functor func = )

                            return func(x);



                            Obligatory godbolt.






                            share|improve this answer



























                              1














                              1










                              1









                              Just for fun, in C++20 we have both (1) lambdas in unevaluated contexts and (2) lambdas without capture are default constructible. Combine those two and you get:



                              template <typename Functor = decltype([](int a) return a+1; )>
                              int run_new(int x, Functor func = )

                              return func(x);



                              Obligatory godbolt.






                              share|improve this answer













                              Just for fun, in C++20 we have both (1) lambdas in unevaluated contexts and (2) lambdas without capture are default constructible. Combine those two and you get:



                              template <typename Functor = decltype([](int a) return a+1; )>
                              int run_new(int x, Functor func = )

                              return func(x);



                              Obligatory godbolt.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 9 hours ago









                              BarryBarry

                              199k22 gold badges369 silver badges660 bronze badges




                              199k22 gold badges369 silver badges660 bronze badges
























                                  0
















                                  Alternatively to other questions, you can even avoid templates:



                                  int run_new(int x, std::function<int(int)> func = [](int a) return a + 1; )

                                  return func(x);






                                  share|improve this answer






















                                  • 5





                                    Do note that you do incur a cost for this. std::function uses type erasure so you have dynamic allocation and more than likely lose the ability to inline the code.

                                    – NathanOliver
                                    9 hours ago






                                  • 2





                                    @NathanOliver Both GCC and Clang seem to be smart enough to generate the same inlined assembly code for f, which is minimal: godbolt.org/z/uuEeNE. Need to admit I was surprised.

                                    – Daniel Langr
                                    9 hours ago







                                  • 3





                                    @DanielLangr But now the functor has to be copyable

                                    – Artyer
                                    9 hours ago











                                  • @Artyer That's the drawback. The advantage is that you don't need to expose the function definition in a header file.

                                    – Daniel Langr
                                    9 hours ago
















                                  0
















                                  Alternatively to other questions, you can even avoid templates:



                                  int run_new(int x, std::function<int(int)> func = [](int a) return a + 1; )

                                  return func(x);






                                  share|improve this answer






















                                  • 5





                                    Do note that you do incur a cost for this. std::function uses type erasure so you have dynamic allocation and more than likely lose the ability to inline the code.

                                    – NathanOliver
                                    9 hours ago






                                  • 2





                                    @NathanOliver Both GCC and Clang seem to be smart enough to generate the same inlined assembly code for f, which is minimal: godbolt.org/z/uuEeNE. Need to admit I was surprised.

                                    – Daniel Langr
                                    9 hours ago







                                  • 3





                                    @DanielLangr But now the functor has to be copyable

                                    – Artyer
                                    9 hours ago











                                  • @Artyer That's the drawback. The advantage is that you don't need to expose the function definition in a header file.

                                    – Daniel Langr
                                    9 hours ago














                                  0














                                  0










                                  0









                                  Alternatively to other questions, you can even avoid templates:



                                  int run_new(int x, std::function<int(int)> func = [](int a) return a + 1; )

                                  return func(x);






                                  share|improve this answer















                                  Alternatively to other questions, you can even avoid templates:



                                  int run_new(int x, std::function<int(int)> func = [](int a) return a + 1; )

                                  return func(x);







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited 9 hours ago









                                  Biagio Festa

                                  6,4672 gold badges14 silver badges42 bronze badges




                                  6,4672 gold badges14 silver badges42 bronze badges










                                  answered 9 hours ago









                                  Daniel LangrDaniel Langr

                                  8,80328 silver badges53 bronze badges




                                  8,80328 silver badges53 bronze badges










                                  • 5





                                    Do note that you do incur a cost for this. std::function uses type erasure so you have dynamic allocation and more than likely lose the ability to inline the code.

                                    – NathanOliver
                                    9 hours ago






                                  • 2





                                    @NathanOliver Both GCC and Clang seem to be smart enough to generate the same inlined assembly code for f, which is minimal: godbolt.org/z/uuEeNE. Need to admit I was surprised.

                                    – Daniel Langr
                                    9 hours ago







                                  • 3





                                    @DanielLangr But now the functor has to be copyable

                                    – Artyer
                                    9 hours ago











                                  • @Artyer That's the drawback. The advantage is that you don't need to expose the function definition in a header file.

                                    – Daniel Langr
                                    9 hours ago













                                  • 5





                                    Do note that you do incur a cost for this. std::function uses type erasure so you have dynamic allocation and more than likely lose the ability to inline the code.

                                    – NathanOliver
                                    9 hours ago






                                  • 2





                                    @NathanOliver Both GCC and Clang seem to be smart enough to generate the same inlined assembly code for f, which is minimal: godbolt.org/z/uuEeNE. Need to admit I was surprised.

                                    – Daniel Langr
                                    9 hours ago







                                  • 3





                                    @DanielLangr But now the functor has to be copyable

                                    – Artyer
                                    9 hours ago











                                  • @Artyer That's the drawback. The advantage is that you don't need to expose the function definition in a header file.

                                    – Daniel Langr
                                    9 hours ago








                                  5




                                  5





                                  Do note that you do incur a cost for this. std::function uses type erasure so you have dynamic allocation and more than likely lose the ability to inline the code.

                                  – NathanOliver
                                  9 hours ago





                                  Do note that you do incur a cost for this. std::function uses type erasure so you have dynamic allocation and more than likely lose the ability to inline the code.

                                  – NathanOliver
                                  9 hours ago




                                  2




                                  2





                                  @NathanOliver Both GCC and Clang seem to be smart enough to generate the same inlined assembly code for f, which is minimal: godbolt.org/z/uuEeNE. Need to admit I was surprised.

                                  – Daniel Langr
                                  9 hours ago






                                  @NathanOliver Both GCC and Clang seem to be smart enough to generate the same inlined assembly code for f, which is minimal: godbolt.org/z/uuEeNE. Need to admit I was surprised.

                                  – Daniel Langr
                                  9 hours ago





                                  3




                                  3





                                  @DanielLangr But now the functor has to be copyable

                                  – Artyer
                                  9 hours ago





                                  @DanielLangr But now the functor has to be copyable

                                  – Artyer
                                  9 hours ago













                                  @Artyer That's the drawback. The advantage is that you don't need to expose the function definition in a header file.

                                  – Daniel Langr
                                  9 hours ago






                                  @Artyer That's the drawback. The advantage is that you don't need to expose the function definition in a header file.

                                  – Daniel Langr
                                  9 hours ago












                                  0
















                                  The best I can imagine pass through a variable



                                  static constexpr auto defFunc = [](int a) return a+1; ;

                                  template <typename Functor = decltype(defFunc)>
                                  int run_new(int x, Functor func = defFunc)

                                  return func(x);






                                  share|improve this answer





























                                    0
















                                    The best I can imagine pass through a variable



                                    static constexpr auto defFunc = [](int a) return a+1; ;

                                    template <typename Functor = decltype(defFunc)>
                                    int run_new(int x, Functor func = defFunc)

                                    return func(x);






                                    share|improve this answer



























                                      0














                                      0










                                      0









                                      The best I can imagine pass through a variable



                                      static constexpr auto defFunc = [](int a) return a+1; ;

                                      template <typename Functor = decltype(defFunc)>
                                      int run_new(int x, Functor func = defFunc)

                                      return func(x);






                                      share|improve this answer













                                      The best I can imagine pass through a variable



                                      static constexpr auto defFunc = [](int a) return a+1; ;

                                      template <typename Functor = decltype(defFunc)>
                                      int run_new(int x, Functor func = defFunc)

                                      return func(x);







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 9 hours ago









                                      max66max66

                                      45.4k7 gold badges48 silver badges80 bronze badges




                                      45.4k7 gold badges48 silver badges80 bronze badges






























                                          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%2f57791248%2fdefault-argument-for-a-functor-in-a-templated-parameter%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

                                          Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                          Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                          Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її