C++: std::any

C++: std::any

04-04-2022 04-04-2022

C++, Game, Code

C++17 has introduced a standard type-safe container, called std::any, that can hold value of any type.
C++17 introduziu um contêiner chamado std::any que pode conter um valor de qualquer tipo.
     
Now we have a type-safe way to store multiple types of values in a single variable.
Agora temos uma maneira segura de armazenar vários tipos de valores em uma única variável.
To use we have to include the header:
Para usar, temos que incluir o cabeçalho:
#include <any>
Creating a variable and reading it's value:
Criando uma variável e lendo seu valor:
std::any a = 1;
std::any_cast<int>(a);
Example storing different types of data in one variable:
Exemplo gravando diferente tipos de dados em uma variável:
#include <iostream>
#include <string>
#include <any>

int main() {
    // Testing int
    std::any a = 1;
    int b = 1;
    std::cout << std::any_cast<int>(a) << " + " << b << " = " << std::any_cast<int>(a)+b << std::endl;

    // Testing double
    a = 10.5;
    double c = 1.2;
    std::cout << std::any_cast<double>(a) << " + " << c << " = " << std::any_cast<double>(a)+c << std::endl;

    // Testing std::string
    a = std::string("TEST");
    std::string d = " STRING";
    std::cout << std::any_cast<std::string>(a) << " + " << d << " = " << std::any_cast<std::string>(a)+d << std::endl;

    return 0;
}

 
 
 
 
 

完了