I want to write a class such that I can define its template type in the class declaration (ie class AChar : public A<char>), and then be able to pass derived classes into functions which accept the parent class, as I would with a non-templated parent class. Is there a way to do this or some way to achieve the same effect?
#include <iostream>
template <class T>
struct A
{
  T value;
  A(T t) : value(t) {};
  virtual void say() const = 0;
};
struct AChar : public A<char>
{
  AChar(char c) : A(c) {};
  void say() const
  {
    std::cout << "A char: " << this->value << std::endl;
  }
};
struct ABool : public A<bool>
{
  ABool(bool b) : A(b) {};
  void say() const
  {
    std::cout << "A bool: " << this->value << std::endl;
  }
};
void makeSay(A a)
{
  a.say();
}
int main()
{
  AChar aChar('g');
  ABool aBool(true);
  makeSay(aChar); // A char: g
  makeSay(aBool); // A bool: 1
}
I want to write a class for the binary representation of a data type. For this, I have a class DataType which is extended by various data type classes (eg IntType, BoolType, ShortType, etc) as posted below. I want to be able to pass these derived classes into a function which can handle any of those types on a binary level. I've posted header files below:
datatype.h
#ifndef _DATATYPE_H_
#define _DATATYPE_H_
#include <cstddef>
template<class T>
class DataType
{
public:
  std::size_t sizeOf() const;
  virtual void toBytes(const T&, char*) const = 0;
  virtual T fromBytes(char*) const = 0;
  virtual T zero() const = 0;
};
#endif
bytetype.h
#ifndef _BYTETYPE_H_
#define _BYTETYPE_H_
#include "numerictype.h"
class ByteType : public NumericType<char>
{
public:
  ByteType();
  void toBytes(char, char[1]) const;
  char fromBytes(char[1]) const;
  char zero() const;
};
#endif
chartype.h
#ifndef _CHARTYPE_H_
#define _CHARTYPE_H_
#include <cstddef>
#include <string>
#include "datatype.h"
class CharType : public DataType<std::string>
{
  std::size_t length;
public:
  static const char PADDING = ' ';
  CharType();
  CharType(size_t);
  std::size_t getLength() const;
  std::size_t sizeOf() const;
  void toBytes(const std::string&, char*) const;
  std::string fromBytes(char*) const;
  std::string zero() const;
};
#endif
example use
void writeToFile(DataType d)
{
  // ...
}
int main()
{
  CharType c(1);
  ByteType b;
  writeToFile(c);
  writeToFile(b);
}
 
    