Home > Software engineering >  How do i pass initial setup values to a templated class in a succinct way?
How do i pass initial setup values to a templated class in a succinct way?

Time:01-18

this is a VERY simplified version of the question to make it obvious what i am asking. I cannot seem to find it on Stack Overflow but i am probably searching using the wrong words!

Here is a Template Class with the obvious parts removed.

template <class T, bool clip = true>
class BOUNDED_VAL { 
    public:     
        BOUNDED_VAL(T initialMin, T intialMax) :locked(false) {     
            assert_or_throw(intialMax >= initialMin, HD_ERR_MINMAX_REVERSED);
            min = initialMin;
            max = intialMax;
            value = initialMin;
        };etc.

// assert_or_throw is a typedef which asserts during debug builds to prevent programmer mistakes (especially my own) or throws a rich catachable runtime error for user input just in case something gets around user input limit checking during release builds (A hard wall). Belt and braces approach...

Now i know i can set this up as an initialised private class member variable like so:

private:
    BOUNDED_VAL<int> testBoundInt = BOUNDED_VAL<int>(0, 10);

BUT

  1. Does this create a new BOUNDED_VAL and then copy it over the member variable (or compiler smooshes this away during optimisation)?

  2. Is there a more succinct way of doing it which i am just not finding? I know the following do not work but for example:

private:
    BOUNDED_VAL<int> testBoundInt(0,10);

or

private:
    BOUNDED_VAL<int>(0,10) testBoundInt;

I am self taught in C so it might be an obvious question...but you never know...

Many Thanks

CodePudding user response:

I know the following do not work but for example:

private:
   BOUNDED_VAL<int> testBoundInt(0,10);

But this will work, provided your compiler was written in the last decade:

BOUNDED_VAL<int> testBoundInt{0,10};

It looks like you might be using an outdated textbook to learn C that does not cover uniform initialization syntax from the current version of C . You are strongly encouraged to get updated learning material.

Does this [copy initialization] create a new BOUNDED_VAL and then copy it over the member variable (or compiler smooshes this away during optimisation)?

This actually depends on the C version your compiler supports, and is configured to use. Depending on several factors it gets "smooshed" away, or we take a scenic trip to the countryside, where an object gets constructed, then a second object gets copy-constructed, and the first object deleted.

But this is now a secondary topic, since uniform initialization syntax solves the original problem.

  • Related