Reputation: 712
In the following code, why no recursive instantiate
template <class T, T v>
struct integral_constant {
static constexpr T value = v;
using value_type = T;
using type = integral_constant<T, v>; // no recurse?
constexpr operator value_type() const noexcept {
return value;
}
constexpr value_type operator()() const noexcept {
return value;
}
};
int main() {
integral_constant<long, 1> l;
integral_constant<long, 1>::type use_type;
return 0;
}
compiler explorer cpp insights
I think this comment by pasbi has answered this question.
Upvotes: 0
Views: 43
Reputation: 36389
Your code does result in infinite recursion, you can use
integral_constant<long, 1>::type::type::type
as many times as you like.
This isn't a problem though as the compiler only instantiates templates that you are using not all the templates that you could possibly use.
You would have an error if you tried to declare a member recursively:
template <class T, T v>
struct integral_constant {
static constexpr T value = v;
using value_type = T;
using type = integral_constant<T, v>;
type member;
constexpr operator value_type() const noexcept {
return value;
}
constexpr value_type operator()() const noexcept {
return value;
}
};
Upvotes: 1