If i have for example some template struct, and i want to give it a user-defined size for some member i can do it by passing a value to constructor like so:
template <typename T>
struct Foo {
int m_size;
Foo(int u_size)
:
m_size {u_size}
{
}
};
and i can also do it by having a non-type template parameter (kinda the way std::array
does it), like so:
template <typename T, int u_size>
struct Foo {
int m_size;
Foo()
:
m_size {u_size}
{
}
};
My question is, what is the difference between these two methods, and when is it useful to use either of them?
u_size
for everything inside the class.std::array
needs itssize
to be known at compile time, it wouldn't work otherwise as it has something likeT data[size];
as data member. So if it works for you with an constructor argument, that is probably (i.e. in most situations) the way to go.const
m_size
andu_size
differ at runtime seems like a bad idea. Having aconst
member is a very bad idea as well. And yes, one can probably find some weird use-case were these would be sensible things to do, but it would be exceedingly rare.2
a template parameter, but you cannot exclude that there is one where it would make sense