C++ templates

I am trying to develop a linked list of structures containing different types.

I have read quite a few different websites' content regarding C++ templates. I am finding the examples and explanations either too simplistic, or overly involved explanations, but still simplistic examples.

So I am doing a Goldilocks and the three bears and asking if anyone can suggest a good resource (URL or ebook) that is not too heavy, and not too light, but just right.

I learn far better from being hands on, so am playing with the concept in some code I am developing, but a good intro that develops into a full-blown example would be appreciated.

I have code working via hand-coded functions and a hard coded array of struct. I went from there to a multi-class with inheritance and class and function templates solution that naturally produced some interesting but nonetheless unhelpful results. I am now going back to square 1 and attempting to develop the template + class solution step by step, iteratively. So the search for a good template intro + examples + development of example resumes.

Any suggestions?

Thanks in advance.

Of course. Having had to describe my problem (only one of them ;)) affords me a useful search expression to use, and I am turning up helpful links via the expression, “linked list of different data types”. I honestly did not expect such a narrow search term to be useful. Glad to be proven wrong.

So thanks for being here, forum, you’ve helped me already :smiley:

It's a little unusual to have a linked list of different types. Why do you require this? If the different types are small you could use a union. Failing that a pointer to a union. The standard template library (STL) does a very good implementation of linked lists (amongst a lot of other things).

I'm already using a union with my hand-coded functions, so that solution is up and running. Rather than use a union, I wanted to use templates. Rather than use an array (of compile-time fixed size), I wanted to create a linked list. That's the progression of my thought process, leading me to a linked list of different types.

I'll check out STL (thanks).

What I'm really looking for is a template tutorial. Regardless of whether I can do what I want here, templates are going to be useful.

Templates let you share functionality between different types. For example (in the STL and other places) you can write a single sort function that will sort multiple types, because the sort is templated. Similarly for linked lists and so on.

However the “multiple” refers to being able to have one function that works with multiple types, one at a time. It doesn’t mean a single list of multiple types, but multiple lists of a single type.

Yeah. Which is why I want a good template tutorial. Because words are not as good as pictures, which are not as good as actually programming something, hands on, when it comes to my learning style.

Hence the request for a good template tutorial resource.

If I find one I'll post it here.

I'm muddling my way through. I have no idea how I would be able to do this pre-internet. What a brilliant learning tool.

I have no idea how I would be able to do this pre-internet.

There used to be things called libraries… 8)

PaulS:

I have no idea how I would be able to do this pre-internet.

There used to be things called libraries... 8)

Pretty sure they were shut by 9pm. Rarely saw the latest programming books in 'em either.
And a book rarely has an example as varied as the ones you find online.

Pretty sure they were shut by 9pm.

Required planning. What a concept!

Rarely saw the latest programming books in 'em either.

But, they could be obtained with an inter-library loan. Yeah, I know. Requires you to understand ALL the capabilities of the library system.

And a book rarely has an example as varied as the ones you find online.

But, it covers the concepts. Application of the concepts is up to the researcher.

PaulS:

Pretty sure they were shut by 9pm.

Required planning. What a concept!

Consistent condescending belligerence and sarcasm from a forum oldbie, what a concept!

Rarely saw the latest programming books in 'em either.

But, they could be obtained with an inter-library loan. Yeah, I know. Requires you to understand ALL the capabilities of the library system.

Not if they weren't anywhere in the library system. Yes, I know. An inter-library loan required that the book had been bought, entered into the sytem, and was not currently on loan and did not have any holds on it. A less than infinte budget means guess what!? Not every single book was available. ZOMG!! Imagine that!!

And a book rarely has an example as varied as the ones you find online.

But, it covers the concepts. Application of the concepts is up to the researcher.

It might cover the concepts. It's not guaranteed though.

The Internet trumps the library. Hands down.

Now then. How brilliant are void pointers!?

I now have an array of base class pointers that act like any sort of type via template class and function definitions, with a little bit of polymorphism, virtual method and void pointer manipulation thrown in for good measure.

I should be able to go from this point to linked lists, so my array does not need to be defined at compile time to a fixed length.

Tomorrow. :smiley:

I have absolutely no idea what I am doing, but it works for my currently very limited test suite, and that’s the main thing:

class baseClass {
    protected:
        bool isDone;
        bool isPin;
    public:
        baseClass() {isDone = false;};
        virtual void debug() {};
        virtual bool isEqual(void *thisVarPtr) {};
};


template <typename T1, typename T2>
class childClass :  public baseClass {
    private:
        T1 variableName;
        T2 lastValue;
        T2 *variablePtr;
    public: 
        childClass(T1 thisVariableName, T2 &thisVariable, bool thisIsPin = false) {
            isPin = thisIsPin;
            variableName = thisVariableName; 
            variablePtr = &thisVariable;
            lastValue = thisVariable;
        };
        virtual void debug() {
            if ((!isDone) || (*variablePtr != lastValue)) {
                isDone = true;
                lastValue = *variablePtr;
                Serial.print(variableName);
                Serial.print(" == ");
                Serial.println(*variablePtr);
            }
        };
        virtual bool isEqual(void *thisVarPtr) { return (thisVarPtr == variablePtr); };
};

template <typename T1, typename T2>
baseClass *newChild(T1 thisVariableName, T2 &thisVariable) {
    return new childClass<T1, T2>(thisVariableName, thisVariable);
};

int varCounter = 0;
baseClass *bArray[10];

template <typename T>
void debug(T &thisVariable) {
    for (int i = 0; i < varCounter; i++) {
        if (bArray[i] -> isEqual(&thisVariable)) {
            bArray[i] -> debug();
            break;
        }
    }
};

Something tells me I am going to have to specialise some templates where a memcopy is required to save the last println'd value of a variable. I can modify the comparison portion of the debug routine at the same time. I was considering comparing only a limited part of the value in that instance, although a strcmp makes the code look pretty minimal regardless.

Certainly nicer doing it this way than instantiating each version of the functions add / debug(var) / debug(name + var) by hand.

Using void pointers, and memcpy, are basically side-stepping all of the type-checking that has been built into C over the years.

I’m wondering why you need to do this? I’ve seen threads before where people try to work around perceived language restrictions without stating what their true goal is. Once revealed, there is usually an easier way to do things.

I am storing references to variables in order to see if they have changed and act accordingly.

This site has been the pretty useful: http://www.cprogramming.com/tutorial/template_specialization.html

Partial template specialization. You can specify types but also values for the template. First time I saw that. That’s really cool.

The example he provides

template <typename T, unsigned length>
class fixedVector { ... };

is immediately useful for my exercise. :smiley:

That page also answers a question I had been considering, and already decided on the most logical answer.

A final implementation detail comes up with partial specializations: how does the compiler pick which specialization to use if there are a combination of completely generic types, some partial specializations, and maybe even some full specializations? The general rule of thumb is that the compiler will pick the most specific template specialization–the most specific template specialization is the one whose template arguments would be accepted by the other template declarations, but which would not accept all possible arguments that other templates with the same name would accept.

aarondc:
I am storing references to variables in order to see if they have changed and act accordingly.

More detail?