使用 boost::variant C++ 的隐式运算符重载

Implicit operator overloading with boost::variant C++

谁能指导我如何解决这个问题。 我有一个 boost::variant.

typedef boost::variant <
int,
std::string,
bool,
double,
vector<int>,
vector<string>,
vector<bool>,
vector<double>
> boostVar;

我正在尝试创建重载 [] 运算符作为 class ABC 的成员函数,类似这样(这只是一个虚拟实现)

class ABC
{
    //some map of (key, value) pair that where key is string and value is of type boostVar
    boostVar [](const string key)
    {
       boostVar temp;
       //some operation that fills up temp based on value of key
       return temp;
    }
}

因此,在使用此实现检索特定值时,它会强制用户指定

int key1Val         = boost::get<int>(ABC["KEY1"]);
bool key2Val        = boost::get<bool>(ABC["KEY2"]);
vector<int> key3Val = boost::get<vector<int>>(ABC["KEY3"]);

我的问题是:

如果我想访问如下所示的值,我应该如何实现它 (i.e. without boost::get<>)

int key1Val         = ABC["KEY1"];
bool key2Val        = ABC["KEY2"];
vector<int> key3Val = ABC["KEY3"];

如果说:KEY1 与 int 不匹配,KEY2 与 bool 不匹配等等,实现应该向用户发出警告。

您需要使用 class 来包装 boost 变体并添加转换行为。最简单的情况是——在通常情况下,实际上客户端代码不会尝试使用指向基的指针 delete 动态分配实例 (boost::variant<...>*)——它可能看起来像这样:

struct Variant : boost::variant<int, std::string, ...etc...>
{
    operator int() const { return boost::get<int>(*this); }
    operator std::string() const { return boost::get<std::string>(*this); }
    ...etc...
};

这将提供与 get<> 提供的相同的检查:编译时检查您试图分配给 类型之一的变体 可以 在运行时保持,运行时会检查它是否确实在您尝试从中分配时实际保持确切的目标类型。

如果您不能确定客户端代码不会 delete 通过基础 class 指针,请考虑私有继承或组合(您将需要做更多的工作来公开任何其他 variant 您的客户端代码可能想要访问的功能)。

(ABC::operator[](const std::string& key) const就可以return这样一个Variant).