C++17 has introduced a standard type-safe container, called std::any, that can hold value of any type.
C++17はstd::anyという標準型セーフなコンテナーを導入しました。これは、任意のタイプの直を保持できます。
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;
}
完了