gpt4 book ai didi

c++ - 使用 decltype 的动态多态类型推导

转载 作者:行者123 更新时间:2023-11-28 01:40:52 25 4
gpt4 key购买 nike

<分区>

你能给我一个提示吗,如何使这段代码按我想要的方式工作?我希望 derived_tDerived,但它始终是 Base

#include <iostream>
#include <string>
#include <memory>

struct Base {
virtual std::string me() { return "Base"; }
};

struct Derived : Base {
virtual std::string me() override { return "Derived"; }
};

void foo(std::shared_ptr<Base> ptr) {

using derived_raw_t = decltype(*ptr);
using derived_t = std::remove_reference<derived_raw_t>::type;

derived_t* x = new derived_t();
std::cout << x->me() << std::endl;
}

int main() {

std::shared_ptr<Base> ptr = std::make_shared<Base>(Derived());

foo(ptr);
}

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