gpt4 book ai didi

c++ - 在 C++ 中为类提供可访问的 "not repeat yourself"时,如何设置 "name"?

转载 作者:可可西里 更新时间:2023-11-01 18:29:11 24 4
gpt4 key购买 nike

考虑以下几点:

class Base {
public:
virtual std::string getName() = 0;
...
};

class Derived1 : public Base {
public:
static std::string getClassName() { return("Derived1"); }
std::string getName() { return("Derived1"); }
...
};

class Derived2 : public Base {
public:
static std::string getClassName() { return("Derived2"); }
std::string getName() { return("Derived2"); }
...
};

这个想法是,如果你将派生类作为模板参数传递,那么你可以通过 getClassName 获取它的类名,而如果你将它作为指向基类的指针传递类,可以通过getName获取名称。

我在这里似乎有很多类似的问题,但他们似乎都在问诸如“我如何使用静态虚拟”、“为什么静态虚拟不存在”之类的问题,以及诸如此类的各种问题,答案似乎比我认为真正的潜在问题更能解决这个问题,即:我怎样才能避免在使用尽可能少的样板文件的同时重复自己的代码并两次提及名称? (不要重复自己,或 DRY 规则)

我也不想要宏。

最佳答案

首先,您可以在 getName 中重复使用 getClassName:

class Derived1 : public Base {
public:
static std::string getClassName() { return("Derived1"); }
std::string getName() override { return getClassName(); }
...
};

现在,getName() 的所有定义都是相同的,因此您可以将它们放在一个宏中以节省键入时间(并使它们更适合 future ):

#define GET_NAME() std::string getName() override { return getClassName(); }

class Derived1 : public Base {
public:
static std::string getClassName() { return("Derived1"); }
GET_NAME()
...
};

或者您也可以在其中捆绑 getClassName:

#define GET_NAME(maName) \
static std::string getClassName() { return(maName); } \
std::string getName() override { return getClassName(); }

class Derived1 : public Base {
public:
GET_NAME("Derived1")
...
};

你说“我也不想要宏”,但宏是一个很好的工具,我认为像这样使用它们不会有任何问题。但是,如果这不是您想要的,您也可以在没有它们的情况下完成:

template <class Self>
struct GetName : public Base
{
std::string getName() override { return Self::getClassName(); }
};

class Derived1 : public GetName<Derived1> {
public:
static std::string getClassName() { return("Derived1"); }
...
};

class Derived2 : public GetName<Derived2> {
public:
static std::string getClassName() { return("Derived2"); }
...
};

关于c++ - 在 C++ 中为类提供可访问的 "not repeat yourself"时,如何设置 "name"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39031971/

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