不使用RTTI检查std::any的类型
创始人
2024-12-29 08:00:13
0

要使用std::any类型,而不使用RTTI来检查其类型,可以使用访问者模式来实现。

首先,定义一个访问者基类,其中包含虚拟的Visit函数,用于处理具体的类型。

class Visitor {
public:
    virtual ~Visitor() = default;
    virtual void Visit(int value) = 0;
    virtual void Visit(const std::string& value) = 0;
    // 添加其他需要处理的类型的Visit函数
};

然后,为每个可能的类型创建一个访问者类,实现对应类型的Visit函数。

class IntVisitor : public Visitor {
public:
    void Visit(int value) override {
        // 处理int类型的值
    }
    
    void Visit(const std::string& value) override {
        // 错误处理,不应该访问到此类型
    }
};

class StringVisitor : public Visitor {
public:
    void Visit(int value) override {
        // 错误处理,不应该访问到此类型
    }
    
    void Visit(const std::string& value) override {
        // 处理std::string类型的值
    }
};

// 添加其他需要处理的类型的访问者类

接下来,创建一个std::any对象,并使用访问者模式进行类型分发。

void ProcessAny(const std::any& value) {
    std::shared_ptr visitor;
    
    if (value.type() == typeid(int)) {
        visitor = std::make_shared();
    } else if (value.type() == typeid(std::string)) {
        visitor = std::make_shared();
    }
    // 添加其他需要处理的类型的判断
    
    if (visitor) {
        if (auto intValue = std::any_cast(&value)) {
            visitor->Visit(*intValue);
        } else if (auto stringValue = std::any_cast(&value)) {
            visitor->Visit(*stringValue);
        }
        // 添加其他需要处理的类型的判断
    }
}

最后,可以通过调用ProcessAny函数来处理std::any对象。

int main() {
    std::any value = 42;
    ProcessAny(value);
    
    std::any strValue = std::string("Hello");
    ProcessAny(strValue);
    
    return 0;
}

注意,这种方法要求提前知道std::any可能包含的类型,并为每个可能的类型创建一个对应的访问者类。如果有新的类型加入,还需要相应地更新代码。

相关内容

热门资讯

玩家必看秘籍(WPK机器人)外... 玩家必看秘籍(WPK机器人)外挂透明挂辅助工具(透视)果真真的有挂(2025已更新)(哔哩哔哩);W...
实操分享(WPK辅助)外挂透明... 实操分享(WPK辅助)外挂透明挂辅助机制(辅助挂)发牌机制(揭秘有挂)-哔哩哔哩这是由厦门游乐互动科...
分辨真假!Wepoke辅助器(... 1、分辨真假!Wepoke辅助器(wePOKE)外挂透明挂辅助工具(辅助挂)科技教程(有挂详细)-哔...
五分钟了解(governoro... 五分钟了解(governorofpoker3辅助)外挂透明挂辅助器(辅助挂)透视辅助(确实有挂)-哔...
透明科技(Wepoke自建房)... 1、透明科技(Wepoke自建房)外挂透明挂辅助机制(透视)其实真的有挂(2022已更新)(哔哩哔哩...
来一盘(Wepoke必胜)外挂... 来一盘(Wepoke必胜)外挂透明挂辅助APP(辅助挂)德州ai机器人(发现有挂)-哔哩哔哩是一款可...
透视脚本!pokerist(w... 透视脚本!pokerist(wePokE)外挂透明挂辅助挂(透视)力荐教程(有挂解惑)-哔哩哔哩;揭...
总算了解(德扑ai人工智能)外... 总算了解(德扑ai人工智能)外挂透明挂辅助软件(辅助挂)透视辅助(有挂头条)-哔哩哔哩1、这是跨平台...
1分钟了解(aapoker讲解... 1分钟了解(aapoker讲解)外挂透明挂辅助插件(透视)确实是真的有挂(2022已更新)(哔哩哔哩...
揭秘一下(德扑操作)外挂透明挂... 揭秘一下(德扑操作)外挂透明挂辅助神器(辅助挂)发牌规律(有挂头条)-哔哩哔哩相信很多朋友都在电脑上...