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
How did medieval manors handle population growth? Were there room for more fields to be ploughed?
Is there a better way to use C# dictionaries than TryGetValue?
Stolen MacBook should I worry about my data?
Another "Ask One Question" Question
Do multi-engine jets need all engines with equal age to reduce asymmetry in thrust and fuel consumption arising out of deterioration?
Why did the population of Bhutan drop by 70% between 2007 and 2008?
Drawing probabilities on a simplex in TikZ
Are spot colors limited and why CMYK mix is not treated same as spot color mix?
Why doesn't Starship have four landing legs?
If the UK Gov. has authority to cancel article 50 notification, why do they have to agree an extension with the EU
Is allowing Barbarian features to work with Dex-based attacks imbalancing?
Is Nikon D500 a good fit for nature and ambient-lighting portraits and occasional other uses?
Alternatives to Network Backup
Notice period 60 days but I need to join in 45 days
Why is there not a willingness from the world to step in between Pakistan and India?
How could a self contained organic body propel itself in space
Is there an in-universe explanation given to the senior Imperial Navy Officers as to why Darth Vader serves Emperor Palpatine?
Should I use the words "pyromancy" and "necromancy" even if they don't mean what people think they do?
How is std::optional never "valueless by exception"?
Should I judge the efficacy of Samadhi based on the ethical qualities of the meditator?
Is this password scheme legit?
Cutting numbers into a specific decimals
What ways are there to "PEEK" memory sections in (different) BASIC(s)
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;
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
add a comment |
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
If it can potentially be called, it needs to exist.
– Jesper Juhl
8 hours ago
2
In this caseconstexpr int f(int N);
(Orconsteval
in c++20) would also work.
– Artyer
8 hours ago
1
Sidenote: What would be the result off<-1>()
? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writingf<-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
8 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 reasonsconstexpr
was created.
– Omnifarious
8 hours ago
add a comment |
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
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
c++ templates recursion template-specialization factorial
asked 9 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 caseconstexpr int f(int N);
(Orconsteval
in c++20) would also work.
– Artyer
8 hours ago
1
Sidenote: What would be the result off<-1>()
? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writingf<-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
8 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 reasonsconstexpr
was created.
– Omnifarious
8 hours ago
add a comment |
If it can potentially be called, it needs to exist.
– Jesper Juhl
8 hours ago
2
In this caseconstexpr int f(int N);
(Orconsteval
in c++20) would also work.
– Artyer
8 hours ago
1
Sidenote: What would be the result off<-1>()
? As it is meaningless, I'd prefer unsigned int as template parameter. We wouldn't prevent anybody from writingf<-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
8 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 reasonsconstexpr
was created.
– Omnifarious
8 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
8 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
8 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
8 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
8 hours ago
add a comment |
2 Answers
2
active
oldest
votes
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.
add a comment |
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 :- )
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
edited 8 hours ago
answered 8 hours ago
NathanOliverNathanOliver
114k19 gold badges181 silver badges259 bronze badges
114k19 gold badges181 silver badges259 bronze badges
add a comment |
add a comment |
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 :- )
add a comment |
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 :- )
add a comment |
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 :- )
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 :- )
edited 8 hours ago
answered 8 hours ago
Igor GIgor G
58010 bronze badges
58010 bronze badges
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
If it can potentially be called, it needs to exist.
– Jesper Juhl
8 hours ago
2
In this case
constexpr int f(int N);
(Orconsteval
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 writingf<-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
8 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
8 hours ago