This has come up before in the past and many people asked how to do it. I will put it here for reference. This will allow you to pass the template object directly into your own functions.
Now, we can't create and use a pointer to a template object, we can only do it's base class. So this will never work:
This is because the runtime function has no idea what the template parameters are to be passed in with the template object.
But with the base class, this is valid:
Although this works for a base class pointer, you can still pass a template object of that base in, however the problem here is when you call functions that exist in the main class (FlexCAN_T4) that do not exist in the base class (FlexCAN_T4_Base), you'll get an error. So you are limited by the base class function accesses for both base and template objects.
Now the solution is very simple actually to have a template object being passed into a regular function that is capable of access all of the main class's function calls. Simply change to this:
Now the actual template object will be able to fully run within your function without the limits of the base class!
Now, we can't create and use a pointer to a template object, we can only do it's base class. So this will never work:
Code:
void configure_CAN(FlexCAN_T4* bus, uint32_t bitrate) {
// DoSomething();
}
This is because the runtime function has no idea what the template parameters are to be passed in with the template object.
But with the base class, this is valid:
Code:
void configure_CAN(FlexCAN_T4_Base* bus, uint32_t bitrate) {
// DoSomething();
}
Although this works for a base class pointer, you can still pass a template object of that base in, however the problem here is when you call functions that exist in the main class (FlexCAN_T4) that do not exist in the base class (FlexCAN_T4_Base), you'll get an error. So you are limited by the base class function accesses for both base and template objects.
Code:
[COLOR="#FF0000"]error: 'class FlexCAN_T4_Base' has no member named 'setTX'
bus->setTX(DEF);
error: 'class FlexCAN_T4_Base' has no member named 'setTX'
bus->setTX(DEF);
[/COLOR]
Now the solution is very simple actually to have a template object being passed into a regular function that is capable of access all of the main class's function calls. Simply change to this:
Code:
[COLOR="#008000"]template <class T>[/COLOR]
void configure_CAN([COLOR="#008000"]T bus[/COLOR], uint32_t bitrate) {
bus->setRX(DEF);
bus->setTX(DEF);
}
Now the actual template object will be able to fully run within your function without the limits of the base class!
Code:
configure_CAN(&Can0, 500000);
Code:
template <class T>
void configure_CAN(T bus, uint32_t bitrate) {
bus->onReceive(onReceive) ;
bus->setRX(26);
bus->setTX(25);
bus->begin();
bus->setBaudRate(bitrate);
}
Last edited: