gpt4 book ai didi

c++ - 在 C++ 中如何将类型作为参数传递?

转载 作者:行者123 更新时间:2023-11-30 02:51:30 29 4
gpt4 key购买 nike

我想传递一个类型作为参数(不是变量或引用)。

我有这个工作代码:

执行代码,其中“testState2”是类的名称(即本例中的类型)。 注意它有一个基本类型 state_t:

changeState(new testState2());

改变状态函数:

void state_t::changeState(state_t * new_state)
{
// Check if the state has changed
if (this != new_state)
{
qDebug() << this->name << ": State changed to: " << new_state->name;
delete this;
_state = new_state;
}
else
{
qDebug() << this->name << ": State un-changed";
}
}

在这段代码中,我基本上是在创建一个新的 testState2 实例,但我想进一步简化调用代码。我只想传递类型,如下所示:

    changeState(testState2);

注意:没有“new”,这不是创建实例,只是传递类名,所以:

  1. 这可能吗?
  2. 如果是,怎么做?

最佳答案

C++ 中的类(和一般类型)不是一等值,因此不能传递或存储。

对于类,理论上您可以使用 typeid,但大多数情况下,我发现仅让实例中的虚函数返回字符串和实现“虚构造函数”模式的注册表更有用。

struct Base
{
virtual const char *class_name() = 0;
...
};

struct MyClass : public(Base)
{
virtual const char *class_name() { return "MyClass"; }
...
}

std::map<std::string, Base *(*)()> instance_builders;

关于c++ - 在 C++ 中如何将类型作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19686242/

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