Home > Back-end >  Using template parameter vs constructor argument
Using template parameter vs constructor argument

Time:01-30

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?

CodePudding user response:

You are using u_size to determine the initializer for the member m_size. The difference between the two examples boils down to Foo<T,i> being a different type than Foo<T,j>. Other than being instantiations of the same template (which usually does not mean much) they are totally unrelated. On the other hand, in the first case, any Foo<T> is of the same type Foo<T>, no matter what was the initial value for the member.

If m_size changes at runtime, it is questionable to require an instance that uses 42 as initial value and an instance that uses 24 as initial value to be of different types.

Maybe m_size does not change at runtime, then it can make sense to have the initial value as part of the type (like eg with std::array). Maybe it does change at runtime, but nevertheless there are reasons to have the initial value baked into the type. There is no "better" Or "worse", it depends what you want/need.

  • Related