I am not sure, if it's possible, but take this snippet of code:
#include <stdio.h>
struct car {
float speed;
};
struct bike {
float speed;
};
void drive(float* speed)
{
printf("driving at speed %f\n", *speed);
}
template<typename T>
void drive(T driveable)
{
drive(&driveable->speed);
}
int main() {
struct car car = { .speed = 10.f };
struct bike bike = { .speed = 20.f };
drive(&car);
drive(&bike);
}
The idea is that any object that has a member field of type float
and that is named speed
can be used transparently with the function drive
. Thanks to the template-overload function drive
, which passes the member of the template type to the actual drive
free-function.
Is it possible, to combine the template - function with the free-function in a single one? Something along the lines:
template<typename T>
void drive(T driveable)
void drive(float *speed = &driveable->speed)
{
printf("driving at speed %f\n", *speed);
}
Additionally, would there be another, more elegant way to do what I want?