你能切换一个 std::any.type() 吗?

cod*_*der 7 c++ any c++17

我想探索如何使用std::any而不是 void * 或此类构造进行消息传递。所以我创建了一个示例代码来测试这个 - 见下文。

std::any 的使用看起来不错,但我想切换类型以检查 std::any 是哪种类型。这可能是不可能的,而且我知道我可以使用 if/elseif... 块来代替,但是如果我可以创建一个 switch 语句,以便我在具有 10-20 种不同类型的实际代码中使用它,那就太好了它会更具可读性。

#include <string>  
#include <iostream>  
#include <sstream>  
#include <any>  
#include <typeindex>  

struct ints { int a{1}; int b{2}; };
struct strings { std::string a{"string1"}; std::string b{"string2"}; };

void send_msg(std::any item)
{
    switch (item.type().hash_code())       // <------- HERE
    {
        case typeid(ints).hash_code():     // <------- HERE
            std::cout << "ints" << std::endl;
            break;
        case typeid(strings).hash_code():
            std::cout << "strings" << std::endl;
            break;
        default:
            std::cout << "unknown type\n";
    }
}

int main()
{
    strings s;
    send_msg(s);

    ints i;
    send_msg(i);
}

Run Code Online (Sandbox Code Playgroud)

现场示例:https : //godbolt.org/z/xPrMYM

我无法打开 std::any::type 返回的 type_info,但我可以打开hash_code()type_info,但这不是我希望的 constexpr!

所以我还尝试获取类型信息的地址以及我能找到的其他一些技巧。但到目前为止没有运气......

有这样的方法吗?

Sec*_*ndi 1

如果可能的话,我还建议在这里使用一个变体,但对于具体问题:

如果您可以使用 boost 并且 C++17 是您参考的标准:它们提供了扩展的 typeid 处理,也可用于多个编译时检查,请参阅

https://www.boost.org/doc/libs/1_67_0/boost/type_index/ctti_type_index.hpp

它的底层 rawType 是一个 const char* constexpr 并且 typeIndex 本身可以用作 std::type_info 的完美替代品。由于标准保证了这些类型标识符的唯一地址,因此这里甚至应该可以进行简单的地址比较(但不确定为什么这种简化目前在 boost 标头中被注释掉)。

要与any一起使用,您可能必须包装它或使用简单的自己的any类型。