Non-Virtual, But Related¶
Overview¶
Goal: eliminate
virtual
Need dynamic dispatch though (want to store base types polymorphically)
Base class
static_cast<>
, based on a type field that is stored in base classManual virtual dispatch (see
code/unrelated/virtual.h
):switch
based on type field.
Sensor Definitions¶
#pragma once
enum class DerivedType
{
SENSOR1,
SENSOR2,
};
class Sensor
{
public:
Sensor(DerivedType type) : type{type} {}
const DerivedType type;
};
class Sensor1 : public Sensor
{
public:
Sensor1(double temperature)
: Sensor{DerivedType::SENSOR1},
_temperature{temperature} {}
double get_temperature() { return _temperature; }
private:
double _temperature;
};
class Sensor2 : public Sensor
{
public:
Sensor2(double temperature)
: Sensor{DerivedType::SENSOR2},
_temperature{temperature} {}
double get_temperature() { return _temperature; }
private:
double _temperature;
};
Virtual Access¶
#pragma once
#include "sensors.h"
static inline double get_temperature(Sensor* s)
{
switch (s->type) {
case DerivedType::SENSOR1: {
Sensor1* s1 = static_cast<Sensor1*>(s);
return s1->get_temperature();
}
case DerivedType::SENSOR2: {
Sensor2* s2 = static_cast<Sensor2*>(s);
return s2->get_temperature();
}
}
return -273.15; // <--- never reached
}
Average Across Many¶
#pragma once
#include "virtual.h"
double average(auto& sensors) // <--- abbreviated function template
{
double sum = 0;
unsigned long num = 0;
for (auto& s: sensors) {
++num;
sum += get_temperature(s);
}
return sum/num;
}
Main Program¶
#include "sensors.h"
#include "avg.h"
#include <iostream>
int main()
{
Sensor1 s1{37.1};
Sensor2 s2{42.666};
Sensor* sensors[] = {&s1, &s2};
std::cout << average(sensors) << std::endl;
return 0;
}