Template factorial function without template specializationStoring C++ template function definitions in a .CPP fileWhy can templates only be implemented in the header file?Where and why do I have to put the “template” and “typename” keywords?Why do we need virtual functions in C++?Simple C++11 constexpr factorial with ternary exceeds maximum template depthTemplate metaprogramming recursion up limits?c++ template class member function specializationHow to create compile-time templatized set/array/vector with fibonacci numbers using templates?Size of std::array in class template depending on template parameterCheck for C++ template value zero fails

Term used to describe a person who predicts future outcomes

Coupling two 15 Amp circuit breaker for 20 Amp

Why did Starhopper's exhaust plume become brighter just before landing?

What is Soda Fountain Etiquette?

How to prevent a hosting company from accessing a VM's encryption keys?

Was the six engine Boeing-747 ever thought about?

Number of Fingers for a Math Oriented Race

The meaning of asynchronous vs synchronous

Shall I fix cracks on bathtub and how to fix them?

Drawing probabilities on a simplex in TikZ

Why is there not a willingness from the world to step in between Pakistan and India?

Should I ask for a raise one month before the end of an internship?

Another "Ask One Question" Question

Is allowing Barbarian features to work with Dex-based attacks imbalancing?

Why does a sticker slowly peel off, but if it is pulled quickly it tears?

To what extent should we fear giving offense?

Why did the population of Bhutan drop by 70% between 2007 and 2008?

Why nature prefers simultaneous events?

What's the point of fighting monsters in Zelda BotW?

Why can't you say don't instead of won't?

Are there any to-scale diagrams of the TRAPPIST-1 system?

What ways are there to "PEEK" memory sections in (different) BASIC(s)

Why does the weaker C–H bond have a higher wavenumber than the C=O bond?

How to handle inventory and story of a player leaving



Template factorial function without template specialization


Storing C++ template function definitions in a .CPP fileWhy can templates only be implemented in the header file?Where and why do I have to put the “template” and “typename” keywords?Why do we need virtual functions in C++?Simple C++11 constexpr factorial with ternary exceeds maximum template depthTemplate metaprogramming recursion up limits?c++ template class member function specializationHow to create compile-time templatized set/array/vector with fibonacci numbers using templates?Size of std::array in class template depending on template parameterCheck for C++ template value zero fails






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








7















I don't understand the following behavior.



The following code, aimed at computing the factorial at compile time, doesn't even compile:



#include <iostream>
using namespace std;
template<int N>
int f()
if (N == 1) return 1; // we exit the recursion at 1 instead of 0
return N*f<N-1>();

int main()
cout << f<5>() << endl;
return 0;



and throws the following error:



...$ g++ factorial.cpp && ./a.out 
factorial.cpp: In instantiation of ‘int f() [with int N = -894]’:
factorial.cpp:7:18: recursively required from ‘int f() [with int N = 4]’
factorial.cpp:7:18: required from ‘int f() [with int N = 5]’
factorial.cpp:15:16: required from here
factorial.cpp:7:18: fatal error: template instantiation depth exceeds maximum of 900 (use ‘-ftemplate-depth=’ to increase the maximum)
7 | return N*f<N-1>();
| ~~~~~~^~
compilation terminated.


whereas, upon adding the specialization for N == 0 (which the template above doesn't even reach),



template<>
int f<0>()
cout << "Hello, I'm the specialization.n";
return 1;



the code compiles and give the correct output of, even if the specialization is never used:



...$ g++ factorial.cpp && ./a.out 
120









share|improve this question
























  • If it can potentially be called, it needs to exist.

    – Jesper Juhl
    8 hours ago






  • 2





    In this case constexpr int f(int N); (Or consteval in c++20) would also work.

    – Artyer
    8 hours ago






  • 1





    Sidenote: What would be the result of f<-1>()? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writing f<-1> (would be converted to huge integer anyway), but at least we'd express right from the start that we actually expect non-negative values only...

    – Aconcagua
    7 hours ago











  • You've gotten an excellent answer that I cannot usefully add to. I just want to state that this is one of the reasons constexpr was created.

    – Omnifarious
    7 hours ago


















7















I don't understand the following behavior.



The following code, aimed at computing the factorial at compile time, doesn't even compile:



#include <iostream>
using namespace std;
template<int N>
int f()
if (N == 1) return 1; // we exit the recursion at 1 instead of 0
return N*f<N-1>();

int main()
cout << f<5>() << endl;
return 0;



and throws the following error:



...$ g++ factorial.cpp && ./a.out 
factorial.cpp: In instantiation of ‘int f() [with int N = -894]’:
factorial.cpp:7:18: recursively required from ‘int f() [with int N = 4]’
factorial.cpp:7:18: required from ‘int f() [with int N = 5]’
factorial.cpp:15:16: required from here
factorial.cpp:7:18: fatal error: template instantiation depth exceeds maximum of 900 (use ‘-ftemplate-depth=’ to increase the maximum)
7 | return N*f<N-1>();
| ~~~~~~^~
compilation terminated.


whereas, upon adding the specialization for N == 0 (which the template above doesn't even reach),



template<>
int f<0>()
cout << "Hello, I'm the specialization.n";
return 1;



the code compiles and give the correct output of, even if the specialization is never used:



...$ g++ factorial.cpp && ./a.out 
120









share|improve this question
























  • If it can potentially be called, it needs to exist.

    – Jesper Juhl
    8 hours ago






  • 2





    In this case constexpr int f(int N); (Or consteval in c++20) would also work.

    – Artyer
    8 hours ago






  • 1





    Sidenote: What would be the result of f<-1>()? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writing f<-1> (would be converted to huge integer anyway), but at least we'd express right from the start that we actually expect non-negative values only...

    – Aconcagua
    7 hours ago











  • You've gotten an excellent answer that I cannot usefully add to. I just want to state that this is one of the reasons constexpr was created.

    – Omnifarious
    7 hours ago














7












7








7








I don't understand the following behavior.



The following code, aimed at computing the factorial at compile time, doesn't even compile:



#include <iostream>
using namespace std;
template<int N>
int f()
if (N == 1) return 1; // we exit the recursion at 1 instead of 0
return N*f<N-1>();

int main()
cout << f<5>() << endl;
return 0;



and throws the following error:



...$ g++ factorial.cpp && ./a.out 
factorial.cpp: In instantiation of ‘int f() [with int N = -894]’:
factorial.cpp:7:18: recursively required from ‘int f() [with int N = 4]’
factorial.cpp:7:18: required from ‘int f() [with int N = 5]’
factorial.cpp:15:16: required from here
factorial.cpp:7:18: fatal error: template instantiation depth exceeds maximum of 900 (use ‘-ftemplate-depth=’ to increase the maximum)
7 | return N*f<N-1>();
| ~~~~~~^~
compilation terminated.


whereas, upon adding the specialization for N == 0 (which the template above doesn't even reach),



template<>
int f<0>()
cout << "Hello, I'm the specialization.n";
return 1;



the code compiles and give the correct output of, even if the specialization is never used:



...$ g++ factorial.cpp && ./a.out 
120









share|improve this question














I don't understand the following behavior.



The following code, aimed at computing the factorial at compile time, doesn't even compile:



#include <iostream>
using namespace std;
template<int N>
int f()
if (N == 1) return 1; // we exit the recursion at 1 instead of 0
return N*f<N-1>();

int main()
cout << f<5>() << endl;
return 0;



and throws the following error:



...$ g++ factorial.cpp && ./a.out 
factorial.cpp: In instantiation of ‘int f() [with int N = -894]’:
factorial.cpp:7:18: recursively required from ‘int f() [with int N = 4]’
factorial.cpp:7:18: required from ‘int f() [with int N = 5]’
factorial.cpp:15:16: required from here
factorial.cpp:7:18: fatal error: template instantiation depth exceeds maximum of 900 (use ‘-ftemplate-depth=’ to increase the maximum)
7 | return N*f<N-1>();
| ~~~~~~^~
compilation terminated.


whereas, upon adding the specialization for N == 0 (which the template above doesn't even reach),



template<>
int f<0>()
cout << "Hello, I'm the specialization.n";
return 1;



the code compiles and give the correct output of, even if the specialization is never used:



...$ g++ factorial.cpp && ./a.out 
120






c++ templates recursion template-specialization factorial






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 8 hours ago









Enrico Maria De AngelisEnrico Maria De Angelis

5742 gold badges10 silver badges21 bronze badges




5742 gold badges10 silver badges21 bronze badges















  • If it can potentially be called, it needs to exist.

    – Jesper Juhl
    8 hours ago






  • 2





    In this case constexpr int f(int N); (Or consteval in c++20) would also work.

    – Artyer
    8 hours ago






  • 1





    Sidenote: What would be the result of f<-1>()? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writing f<-1> (would be converted to huge integer anyway), but at least we'd express right from the start that we actually expect non-negative values only...

    – Aconcagua
    7 hours ago











  • You've gotten an excellent answer that I cannot usefully add to. I just want to state that this is one of the reasons constexpr was created.

    – Omnifarious
    7 hours ago


















  • If it can potentially be called, it needs to exist.

    – Jesper Juhl
    8 hours ago






  • 2





    In this case constexpr int f(int N); (Or consteval in c++20) would also work.

    – Artyer
    8 hours ago






  • 1





    Sidenote: What would be the result of f<-1>()? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writing f<-1> (would be converted to huge integer anyway), but at least we'd express right from the start that we actually expect non-negative values only...

    – Aconcagua
    7 hours ago











  • You've gotten an excellent answer that I cannot usefully add to. I just want to state that this is one of the reasons constexpr was created.

    – Omnifarious
    7 hours ago

















If it can potentially be called, it needs to exist.

– Jesper Juhl
8 hours ago





If it can potentially be called, it needs to exist.

– Jesper Juhl
8 hours ago




2




2





In this case constexpr int f(int N); (Or consteval in c++20) would also work.

– Artyer
8 hours ago





In this case constexpr int f(int N); (Or consteval in c++20) would also work.

– Artyer
8 hours ago




1




1





Sidenote: What would be the result of f<-1>()? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writing f<-1> (would be converted to huge integer anyway), but at least we'd express right from the start that we actually expect non-negative values only...

– Aconcagua
7 hours ago





Sidenote: What would be the result of f<-1>()? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writing f<-1> (would be converted to huge integer anyway), but at least we'd express right from the start that we actually expect non-negative values only...

– Aconcagua
7 hours ago













You've gotten an excellent answer that I cannot usefully add to. I just want to state that this is one of the reasons constexpr was created.

– Omnifarious
7 hours ago






You've gotten an excellent answer that I cannot usefully add to. I just want to state that this is one of the reasons constexpr was created.

– Omnifarious
7 hours ago













2 Answers
2






active

oldest

votes


















12















The issue here is that your if statement is a run time construct. When you have



int f() 
if (N == 1) return 1; // we exit the recursion at 1 instead of 0
return N*f<N-1>();



the f<N-1> is instantiated as it may be called. Even though the if condition will stop it from calling f<0>, the compiler still has to instantiate it since it is part of the function. That means it instantiates f<4>, which instantiates f<3>, which instantiates f<2>, and on and on it will go forever.



The Pre C++17 way to stop this is to use a specialization for 0 which breaks that chain. Starting in C++17 with constexpr if, this is no longer needed. Using



int f() 
if constexpr (N == 1) return 1; // we exit the recursion at 1 instead of 0
else return N*f<N-1>();



guarantees that return N*f<N-1>(); won't even exist in the 1 case, so you don't keep going down the instantiation rabbit hole.






share|improve this answer


































    3















    The problem is that f<N>() always instantiates f<N-1>() whether that if branch is taken or not. Unless properly terminated, that would create infinite recursion at compile time (i.e. it would attempt instantiating F<0>, then f<-1>, then f<-2> and so on). Obviously you should terminate that recursion somehow.



    Apart from constexpr solution and specialization suggested by NathanOliver, you may terminate the recursion explicitly:



    template <int N>
    inline int f()

    if (N <= 1)
    return 1;
    return N * f<(N <= 1) ? N : N - 1>();



    Mind, this solution is rather poor (the same terminal condition must be repeated twice), I'm writing this answer merely to show that there are always more ways to solve the problem :- )






    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%2f57698167%2ftemplate-factorial-function-without-template-specialization%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









      12















      The issue here is that your if statement is a run time construct. When you have



      int f() 
      if (N == 1) return 1; // we exit the recursion at 1 instead of 0
      return N*f<N-1>();



      the f<N-1> is instantiated as it may be called. Even though the if condition will stop it from calling f<0>, the compiler still has to instantiate it since it is part of the function. That means it instantiates f<4>, which instantiates f<3>, which instantiates f<2>, and on and on it will go forever.



      The Pre C++17 way to stop this is to use a specialization for 0 which breaks that chain. Starting in C++17 with constexpr if, this is no longer needed. Using



      int f() 
      if constexpr (N == 1) return 1; // we exit the recursion at 1 instead of 0
      else return N*f<N-1>();



      guarantees that return N*f<N-1>(); won't even exist in the 1 case, so you don't keep going down the instantiation rabbit hole.






      share|improve this answer































        12















        The issue here is that your if statement is a run time construct. When you have



        int f() 
        if (N == 1) return 1; // we exit the recursion at 1 instead of 0
        return N*f<N-1>();



        the f<N-1> is instantiated as it may be called. Even though the if condition will stop it from calling f<0>, the compiler still has to instantiate it since it is part of the function. That means it instantiates f<4>, which instantiates f<3>, which instantiates f<2>, and on and on it will go forever.



        The Pre C++17 way to stop this is to use a specialization for 0 which breaks that chain. Starting in C++17 with constexpr if, this is no longer needed. Using



        int f() 
        if constexpr (N == 1) return 1; // we exit the recursion at 1 instead of 0
        else return N*f<N-1>();



        guarantees that return N*f<N-1>(); won't even exist in the 1 case, so you don't keep going down the instantiation rabbit hole.






        share|improve this answer





























          12














          12










          12









          The issue here is that your if statement is a run time construct. When you have



          int f() 
          if (N == 1) return 1; // we exit the recursion at 1 instead of 0
          return N*f<N-1>();



          the f<N-1> is instantiated as it may be called. Even though the if condition will stop it from calling f<0>, the compiler still has to instantiate it since it is part of the function. That means it instantiates f<4>, which instantiates f<3>, which instantiates f<2>, and on and on it will go forever.



          The Pre C++17 way to stop this is to use a specialization for 0 which breaks that chain. Starting in C++17 with constexpr if, this is no longer needed. Using



          int f() 
          if constexpr (N == 1) return 1; // we exit the recursion at 1 instead of 0
          else return N*f<N-1>();



          guarantees that return N*f<N-1>(); won't even exist in the 1 case, so you don't keep going down the instantiation rabbit hole.






          share|improve this answer















          The issue here is that your if statement is a run time construct. When you have



          int f() 
          if (N == 1) return 1; // we exit the recursion at 1 instead of 0
          return N*f<N-1>();



          the f<N-1> is instantiated as it may be called. Even though the if condition will stop it from calling f<0>, the compiler still has to instantiate it since it is part of the function. That means it instantiates f<4>, which instantiates f<3>, which instantiates f<2>, and on and on it will go forever.



          The Pre C++17 way to stop this is to use a specialization for 0 which breaks that chain. Starting in C++17 with constexpr if, this is no longer needed. Using



          int f() 
          if constexpr (N == 1) return 1; // we exit the recursion at 1 instead of 0
          else return N*f<N-1>();



          guarantees that return N*f<N-1>(); won't even exist in the 1 case, so you don't keep going down the instantiation rabbit hole.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 8 hours ago

























          answered 8 hours ago









          NathanOliverNathanOliver

          114k19 gold badges181 silver badges259 bronze badges




          114k19 gold badges181 silver badges259 bronze badges


























              3















              The problem is that f<N>() always instantiates f<N-1>() whether that if branch is taken or not. Unless properly terminated, that would create infinite recursion at compile time (i.e. it would attempt instantiating F<0>, then f<-1>, then f<-2> and so on). Obviously you should terminate that recursion somehow.



              Apart from constexpr solution and specialization suggested by NathanOliver, you may terminate the recursion explicitly:



              template <int N>
              inline int f()

              if (N <= 1)
              return 1;
              return N * f<(N <= 1) ? N : N - 1>();



              Mind, this solution is rather poor (the same terminal condition must be repeated twice), I'm writing this answer merely to show that there are always more ways to solve the problem :- )






              share|improve this answer































                3















                The problem is that f<N>() always instantiates f<N-1>() whether that if branch is taken or not. Unless properly terminated, that would create infinite recursion at compile time (i.e. it would attempt instantiating F<0>, then f<-1>, then f<-2> and so on). Obviously you should terminate that recursion somehow.



                Apart from constexpr solution and specialization suggested by NathanOliver, you may terminate the recursion explicitly:



                template <int N>
                inline int f()

                if (N <= 1)
                return 1;
                return N * f<(N <= 1) ? N : N - 1>();



                Mind, this solution is rather poor (the same terminal condition must be repeated twice), I'm writing this answer merely to show that there are always more ways to solve the problem :- )






                share|improve this answer





























                  3














                  3










                  3









                  The problem is that f<N>() always instantiates f<N-1>() whether that if branch is taken or not. Unless properly terminated, that would create infinite recursion at compile time (i.e. it would attempt instantiating F<0>, then f<-1>, then f<-2> and so on). Obviously you should terminate that recursion somehow.



                  Apart from constexpr solution and specialization suggested by NathanOliver, you may terminate the recursion explicitly:



                  template <int N>
                  inline int f()

                  if (N <= 1)
                  return 1;
                  return N * f<(N <= 1) ? N : N - 1>();



                  Mind, this solution is rather poor (the same terminal condition must be repeated twice), I'm writing this answer merely to show that there are always more ways to solve the problem :- )






                  share|improve this answer















                  The problem is that f<N>() always instantiates f<N-1>() whether that if branch is taken or not. Unless properly terminated, that would create infinite recursion at compile time (i.e. it would attempt instantiating F<0>, then f<-1>, then f<-2> and so on). Obviously you should terminate that recursion somehow.



                  Apart from constexpr solution and specialization suggested by NathanOliver, you may terminate the recursion explicitly:



                  template <int N>
                  inline int f()

                  if (N <= 1)
                  return 1;
                  return N * f<(N <= 1) ? N : N - 1>();



                  Mind, this solution is rather poor (the same terminal condition must be repeated twice), I'm writing this answer merely to show that there are always more ways to solve the problem :- )







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 7 hours ago

























                  answered 7 hours ago









                  Igor GIgor G

                  58010 bronze badges




                  58010 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%2f57698167%2ftemplate-factorial-function-without-template-specialization%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

                      199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單