我花了一段时间才弄明白,但是 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/any和 http://en.cppreference.com/w/cpp/experimental/any/any_cast
关于c++ - boost::指针与值的任何混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37798118/