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

标签 c++ boost operator-overloading implicit-conversion boost-variant

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

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

我正在尝试创建重载 []运算符作为类的成员函数 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 不匹配等等,实现应该向用户发出警告。

最佳答案

您需要使用一个类来包装 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通过基类指针,考虑私有(private)继承或组合(您将需要做更多工作来公开您的客户端代码可能想要访问的任何其他 variant 功能)。

( ABC::operator[](const std::string& key) const 可以返回这样一个 Variant )。

关于c++ - 使用 boost::variant C++ 的隐式运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46010224/

相关文章:

c++ - fstream 用于读写

c++ - 如何在不构建模块的情况下将 C++ 类公开给 Python

php - 当 PHP、C++ 和 shell 脚本尝试访问同一个文件时,如何避免错误?

c++ - 在一种方法中使用两个 boost 互斥体?

c++ - 运算符重载和多态区别

c++ - 拆分包含逗号分隔条目的字符串流

c++ - 在 Borland C++ 上使用#pragma pack 和#define

c++ - win32::WaitForSingleObject 期间 Windows 上的 Boost.Thread 断言/崩溃

java - 有没有等同于 Boost::Python for Java 的东西?

c++ - 重载的Double Equal运算符无法正常工作