c++ - boost::指针与值的任何混淆

标签 c++ boost boost-any

我花了一段时间才弄明白,但是 boost::any 的语义令人困惑。

对于值类型,您可以像这样使用它:

int value = 100;
boost::any something;
something = value;
//...later...
int value = boost::any_cast<int>(&something);

此代码清晰且有意义,但在内部将 value 存储为拷贝。这意味着对于我放在 boost::any 中的较大对象,它们将被复制。此外,我用此替换 void* 的任何函数都希望在我修改 boost::any 对象中包含的值时修改函数外部的值(它赢得了'发生,因为它复制了它)。

因此,如果我将指针放入其中,事情就会变得很奇怪:

int value = 100;
boost::any something;
something = &value;
//...later...
int* value = *boost::any_cast<int*>(&something);

在这种情况下,我必须取消引用返回值,因为 boost::any_cast 返回 int**!我也没有检查过,但我认为如果 something.empty() == true 可能会崩溃。这一点都不简单。

我不想在我的 boost::any 中存储值,我希望它只对指针起作用并且在语义上表现得更接近 void*。指针输入,指针输出,混合了一些类型安全。基本上我想要的是 boost::any_pointer,或类似的东西。有没有办法禁止 boost::any 接受指针以外的任何东西?如果没有,是否有 boost::any 的替代方案可以提供我正在寻找的语义?

最佳答案

你使用的 any_cast 是错误的:

基本上有两(三)种口味。

  • 获取对任何内容的引用并返回值或对内容的引用
  • 获取指向任何内容的指针并返回指向内容的指针

例子:

#include <boost/any.hpp>
int main()
{
    // Any holding a value
    {
        boost::any any_value(1);
        // Throws bad_any_cast if the content is not 'int' (in this case):
        int  value = boost::any_cast<int>(any_value);
        // Throws bad_any_cast if the content is not 'int' (in this case):
        int& reference = boost::any_cast<int&>(any_value);
        // Returns a null pointer if the content is not 'int' (in this case):
        int* pointer = boost::any_cast<int>(&any_value);
    }

    // Any holding a pointer (which is nothing else but a value)
    {
        int integer = 0;
        boost::any any_ptr(&integer);
        // Throws bad_any_cast if the content is not 'int*' (in this case):
        int * pointer = boost::any_cast<int*>(any_ptr);
        // Throws bad_any_cast if the content is not 'int*' (in this case):
        int*& pointer_reference = boost::any_cast<int*&>(any_ptr);
        // Returns a null pointer if the content is not 'int*' (in this case):
        int** pointer_pointer = boost::any_cast<int*>(&any_ptr);
    }
}

另请参阅:http://en.cppreference.com/w/cpp/experimental/anyhttp://en.cppreference.com/w/cpp/experimental/any/any_cast

关于c++ - boost::指针与值的任何混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37798118/

相关文章:

c# - 在我的计划循环中重新分配 DateTime 对象的值时,DateTime 多线程 UDP 发送方具有非常不同的时间结果

c++ - 如何在构建单线程库时删除 pthread undefined reference

c++ - 如何独立使用 Boost.Filesystem?

c++ - Boost::any 从指针使用时不为空

c++ - 在数组中存储对象

c++ - 使用 'new' 和指针理解 C++ 代码

c++ - 如何在没有 typedef 的情况下进行函数指针转换?

c++ - 通过引用 : TypeError: No to_python (by-value) converter found for C++ type: 调用 Boost.Python

c++ - enable_if 和转换运算符?

c++ - 使用 Boost 预处理器将 Any 提升到 Boost Variant