gpt4 book ai didi

c++ - 在编译时定义多个派生类

转载 作者:行者123 更新时间:2023-11-30 03:25:35 25 4
gpt4 key购买 nike

我希望节省时间,避免在添加新类型时编写重复代码。

我目前拥有的是以下内容:

class BaseClass {
std::string m_name;
public:
BaseClass(const std::string name) : m_name(name) {};
std::string getName(void) { return m_name; }
virtual std::string toString(void) = 0;
};

class DerivedInt8 : public BaseClass {
uint8_t m_value;
public:
DerivedInt8(const uint8_t value, const std::string name) : BaseClass(name), m_value(value) {}

virtual std::string toString(void) {
std::ostringstream os;
os << getName() << ": " << m_value;
return os.str();
}
};

class DerivedInt16 : public BaseClass {
uint16_t m_value;
public:
DerivedInt16(const uint16_t value, const std::string name) : BaseClass(name), m_value(value) {}

virtual std::string toString(void) {
std::ostringstream os;
os << getName() << ": " << m_value;
return os.str();
}
};

我还有一个用于 uint32_t、uint64_t 和其他一些自定义类的派生类。在 C++ 中有没有一种干净的方法我可以定义一个新类型而不必为我决定在未来添加的每个新类型复制代码?在 C 中,我会使用某种形式的 X-Macros 来定义我在编译时需要的一切;我可以使用 C++ 中的镜像吗?

最佳答案

template <typename T>
class Generic : public BaseClass {
T m_value;
public:
Generic(T value, const std::string& name)
: BaseClass(name), m_value(value) {}

std::string toString(void) const override {
std::ostringstream os;
os << getName() << ": " << m_value;
return os.str();
}
};
using DerivedInt8 = Generic<uint8_t>;
using DerivedInt16 = Generic<uint16_t>;

这是非常基础的内容,应该包含在您绝对应该阅读的介绍性文本中。

您还通过值传递 const 参数,这在很大程度上是没有意义的(我假设您的意思是 const std::string&),具有应该是 const 限定的方法( getNametoString),并且在实现虚函数时不要使用 override

关于c++ - 在编译时定义多个派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com