C++:如何将对象作为模板基类传递给函数
C++: How to pass object to function as templated base class
我想写一个类,这样我就可以在类声明中定义它的模板类型(即class AChar : public A<char>
(,然后能够将派生类传递到接受父类的函数中,就像处理非模板父类一样。有没有办法做到这一点,或者有没有办法达到同样的效果?
#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
}
我想为数据类型的二进制表示编写一个类。为此,我有一个类DataType,它由各种数据类型类(如IntType、BoolType、ShortType等(扩展,如下所示。我希望能够将这些派生类传递到一个函数中,该函数可以在二进制级别上处理任何这些类型。我在下面发布了头文件:
数据类型.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
字节类型.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
图表类型.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
示例使用
void writeToFile(DataType d)
{
// ...
}
int main()
{
CharType c(1);
ByteType b;
writeToFile(c);
writeToFile(b);
}
由于基类是模板化的,因此要将多个派生类型传递给的函数必须:
-
本身被模板化,以便接受基类(必须通过引用或指针传递基类以避免切片(。
template<class T> void makeSay(const A<T> &a) { a.say(); }
template<class T> void writeToFile(const DataType<T> &d) { // ... }
-
为每个特定的派生类型重载(哪种类型违背了使用模板的目的(:
void makeSay(const AChar &a) { a.say(); } void makeSay(const ABool &a) { a.say(); }
void writeToFile(const ByteType &t) { // ... } void writeToFile(const CharType &t) { // ... }
相关文章:
- 虚拟基类函数中派生类的大小
- 无法访问基类函数 C++
- 如何使派生类函数在调用时始终调用相同的基类函数?
- C++虚拟函数:基类函数是调用的,而不是派生的
- Qt基类函数定义
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 有没有办法调用基类函数,该函数在使用私有继承的派生类中被覆盖?
- C++ - 基类函数指针调用的替代方法
- 什么更有效率?在重载函数中或通过在基类函数中检查对象类型来实现
- 重载基类函数是不好的做法吗?
- 在 qml 中公开基类函数
- 调用基类函数时强制使用类名?
- 如何判断哪个派生的类对象称为基类函数
- 获取具有基类函数的派生类
- 有没有办法从基类函数参数中推断出模板参数
- 私有非虚拟基类函数被称为派生类中的函数
- 模板基类函数成员的别名
- 如何用相同的签名从main调用基类函数
- C++ 如何从 main 调用派生的基类函数
- memcpy派生类到基类,为什么还调用基类函数