将std :: any转换为未知类型

inn*_*tic 2 c++ c++17

如果我有std::any一个std::string或一个int,我怎么能投清楚交代包含的类型呢?

std::anytype它,但我不能使用这种类型来施放.

例:

#include <any>
#include <iostream>
#include <string>

int main(void) {
    std::any test = "things";
    std::any test2 = 123;

    // These don't work
    std::string the_value = (std::string) test;
    int the_value2 = (int) test2;

    std::cout << the_value << std::endl;
    std::cout << the_value2 << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

CS *_*Pei 9

any_cast用来做这个伎俩.例如

auto a = std::any(12); 
std::cout << std::any_cast<int>(a) << '\n'; 
Run Code Online (Sandbox Code Playgroud)

您可以从cppreference中找到更多详细信息

如果要在a中动态转换std::any,可以尝试

if (a.type() == typeid(int)) {
    cout << std::any_cast<int>(a) << endl;
} else if (a.type() == typeid(float)) {
    cout <<  std::any_cast<float>(a) << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • @innectic类型(`std :: string`和`int`)在你的例子中也是已知的.你能举一个涉及"未知类型"的例子吗? (4认同)

Yak*_*ont 6

如果你没有任何类型的列表,其中any包含一个类型,你不能将any转换为它的类型并作为其真实类型进行操作.

您可以将一个类型存储在any中,并将该类型的操作存储为该类型的函数指针.但是,这必须在存储的时刻进行,或当你这样做有存储在任何可能的类型的列表(可能与1元).

C++也没有内的任何存储足够的信息,以允许任意代码要在该类型编译时,它存储在任何的值.C++在运行时不允许完全"具体化".

键入擦除类型擦除,"任何"问题?由一个名不见经传的stackoverflow用户提供的问答给出了一个例子,说明如何记住对内容的某些操作any仍然忘记了存储的类型.

如果您确实有这样的可能类型列表,请考虑使用variant. any存在于狭窄的窗口中,您不知道在容器设计时存储的类型,但是在插入和移除时都会存在.

在那个狭窄的窗口中,您可以根据存储的typeid进行运行时测试并使用转换为已知类型any_cast.