The N
needs to be compile-time constant, which is with a normal for
loop is not possible.
But, there are many workarounds. For instance, inspired by this SO post, you can do something like the following.
(See a Live demo)
template<size_t N>
class A
{
public:
// make the member function public so that you can call with its instance
void someFunctions()
{
std::cout << N << "\n";
};
};
template<int N> struct AGenerator
{
static void generate()
{
AGenerator<N - 1>::generate();
A<N> a;
a.someFunctions();
}
};
template<> struct AGenerator<1>
{
static void generate()
{
A<1> a;
a.someFunctions();
}
};
int main()
{
// call the static member for constructing 100 A objects
AGenerator<100>::generate();
}
Prints 1
to 100
In c++17, the above can be reduced to a single template AGenerator
class(i.e. specialization can be avoided), using if constexpr
. (See a Live demo)
template<std::size_t N>
struct AGenerator final
{
static constexpr void generate() noexcept
{
if constexpr (N == 1)
{
A<N> a;
a.someFunctions();
// .. do something more with `a`
}
else
{
AGenerator<N - 1>::generate();
A<N> a;
a.someFunctions();
// .. do something more with `a`
}
}
};
Output:
1
2
3
4
5
6
7
8
9
10
In case of providing the range of iteration, you could use the following.(See a Live demo)
template<std::size_t MAX, std::size_t MIN = 1> // `MIN` is set to 1 by default
struct AGenerator final
{
static constexpr void generate() noexcept
{
if constexpr (MIN == 1)
{
A<MIN> a;
a.someFunctions();
// .. do something more with `a`
AGenerator<MAX, MIN + 1>::generate();
}
else if constexpr (MIN != 1 && MIN <= MAX)
{
A<MIN> a;
a.someFunctions();
// .. do something more with `a`
AGenerator<MAX, MIN + 1>::generate();
}
}
};
int main()
{
// provide the `MAX` count of looping. `MIN` is set to 1 by default
AGenerator<10>::generate();
}
Outputs the same as the above version.
N
needs to beconstexpr
which if it is a loop variable that's not the case – Dear