早期我们用union来存变量,但是预先不知道存储的是那种类型.
C++新特性中,提供std::variant来满足新场景
直接干货
#include <unordered_map>
#include <variant>
namespace your_own_sample
{
class SampleTest
{
public:
explicit SampleTest() = default;
SampleTest(const std::string &address, uint16_t port);
~SampleTest() override = default;
using Module = std::string;
using Path = std::string;
using Data = std::string;
using CallBackA = std::function<void(const std::error_code &status,
const Module &module,
const Path &path,
Data *data)>;
void subscribeCallBackA(const Module &module, const Path &path, const CallBackA &opercb) final;
using CallBackB = std::function<void(const std::error_code &status,
const Module &module,
const Path &path,
uint32_t message_id)>;
void subscribeCallBackB(const Module &module,
const Path &path,
const CallBackB &opercb);
private:
using subCB = std::variant<CallBackA, CallBackB>;
std::unordered_map<Path, std::pair<Module, subCB>> subscribe_info_;
void handleSubAsOperationalDPResponse(const Response &resp);
};
void SampleTest::handleSubAsOperationalDPResponse(const Response &resp)
{
auto iter = subscribe_info_.find(resp.path(0));
if (iter != subscribe_info_.end())
{
if (std::holds_alternative<CallBackA>(iter->second.second))
{
Data data;
auto callback = std::get<CallBackA>(iter->second.second);
callback(your_own_api::SUCCESS, resp.module_name(), resp.path(0), &data);
}
else if (std::holds_alternative<CallBackB>(iter->second.second))
{
auto callback = std::get<CallBackB>(iter->second.second);
callback(your_own_api::SUCCESS, resp.module_name(), resp.path(0), resp.message_id());
}
}
}
void SampleTest::subscribeCallBackA(const Module &module,
const Path &path,
const CallBackA &callBackA)
{
subscribe_info_.insert({path, {module, callBackA}});
}
void SampleTest::subscribeCallBackB(const Module &module,
const Path &path,
const CallBackB &callBackB)
{
subscribe_info_.insert({path, {module, callBackB}});
}
}
通过存储的类型不同,来确定该调用哪种回调函数,上述样例只是其中最简单的应用,我们在refine老代码的时候,可以快炫酷的用用,看看效果。