Home > Backend Development > C++ > Can C Store Data of Different Types in a Single Container?

Can C Store Data of Different Types in a Single Container?

DDD
Release: 2024-11-06 03:41:02
Original
326 people have browsed it

Can C   Store Data of Different Types in a Single Container?

Heterogeneous Containers in C

Question:

The STL container classification graphic suggests that there is no STL container that is both variable size and heterogeneous. Does C lack a solution for storing data of different types?

Answer:

While C containers are typically designed to hold objects of a single type, there are ways to store different types of data:

  • Pointers: Use a container of pointers to objects of a common base class, allowing you to store objects of different derived types.
  • boost::any: Store objects of any type in a container. This uses a template metaprogramming approach to handle different types safely.
  • boost::variant: Similar to boost::any, but requires specifying the allowed types at compile time.

Code Example:

<code class="cpp">#include <list>
#include <boost/any.hpp>

using boost::any_cast;
typedef std::list<boost::any> many;

int main() {
    many values;
    append_int(values, 10);
    append_string(values, "Hello");

    if (is_int(values.front())) {
        int number = any_cast<int>(values.front());
        std::cout << number << std::endl;
    }

    return 0;
}</code>
Copy after login

The above is the detailed content of Can C Store Data of Different Types in a Single Container?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template