Islah Amine
Islah Amine

Reputation: 76

LinkedList That Accept Any Type Of Object At Same Time

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.

Upvotes: 0

Views: 128

Answers (1)

Faker
Faker

Reputation: 131

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;
    }
  }
}

Upvotes: 1

Related Questions