同时接受任何类型的对象的链接清单

发布于 2025-01-19 15:45:01 字数 145 浏览 4 评论 0原文

是否可以实现一个同时接受任何类型对象的链表?

例如: list.add(int) 、 list.add(float) 、 list.add(object1) 、 list.add(object2)

正如你所看到的,我在同一个列表中添加了不同的类型。

Is it possible to implement a linkedlist that accept any type of objects at same time ?

for example : list.add(int) , list.add(float) , list.add(object1) , list.add(object2)

as you can see i added different types in the same list.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲性难收 2025-01-26 15:45:01

您可以利用std ::任何来满足您的需求。

有一个示例,说明如何将元素添加到std :: list< std :: Any>以及如何从std :: list< std&std :: Any>中读取元素。

#include <any>
#include <iostream>
#include <list>

int main() {
  std::list<std::any> list;
  list.emplace_back(1);
  list.emplace_back<std::string>("ok");

  for (auto& item : list) {
    if (item.type() == typeid(int)) {
      std::cout << "int : " << std::any_cast<int>(item) << std::endl;
    } else if (item.type() == typeid(std::string)) {
      std::cout << "string : " << std::any_cast<std::string>(item) << std::endl;
    }
  }
}

You can utilize std::any to suit your needs.

There is an example of how to add an element to a std::list<std::any> and how to read an element from a std::list<std::any>.

#include <any>
#include <iostream>
#include <list>

int main() {
  std::list<std::any> list;
  list.emplace_back(1);
  list.emplace_back<std::string>("ok");

  for (auto& item : list) {
    if (item.type() == typeid(int)) {
      std::cout << "int : " << std::any_cast<int>(item) << std::endl;
    } else if (item.type() == typeid(std::string)) {
      std::cout << "string : " << std::any_cast<std::string>(item) << std::endl;
    }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文