我想写一个类,这样我可以在类声明中定义它的模板类型(即 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);
}
最佳答案
由于基类是模板化的,您想要将多个派生类型传递给的函数必须:
本身被模板化,以接受基类(您必须通过引用或指针传递以避免 slicing )。
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++:如何将对象传递给函数作为模板化基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664432/