我的问题有几个部分。我一直在研究如何/何时使用 boost::any
.我想知道是否可以分配一个 struct
到 boost::any
变量。
示例:
struct S {
int x;
};
S s;
s.x = 5;
boost::any var = s;
在我看来这是可能的,但它引出了我的下一个问题。如果这是一个有效的分配,那么我将如何访问数据成员 x
? var
不是 struct
输入,因为它是 boost::any
.
我的下一个问题不依赖于数据成员是否可以访问。那么问题是,如果变量 a
怎么办?类型为 uint8_t
.
示例: 编辑:正如评论中所指出的,下面的代码确实支持 uint8_t 但未打印出来。参见 uint8_t can't be printed with cout .
uint8_t a = 10;
boost::any b = a;
std::cout << boost::any_cast<uint8_t>(b);
我发现可以使用 boost::any_cast
但没有发现它支持无符号类型。当我尝试使用 boost::any_cast<uint8_t>()
它没有打印,但没有抛出错误。是否有可能获得像 uint8_t
这样的类型的值?使用 boost
?如果是怎么办?
我将继续阅读 boost::any 的更多文档但如果有人对这些问题或主题有见解、细节或注释,请发帖,因为我很想了解更多关于它是如何工作的。谢谢!
最佳答案
I was wondering if it is possible to assign a struct to a
boost::any
variable
是的。
How would I access the data member
x
?
您将使用 any_cast<S>(var).x
访问.继续你的例子:
int& the_x_member = any_cast<S>(var).x;
std::cout << "s.x is " << the_x_member << "\n";
What if variable
a
is of typeuint8_t
?
完全有可能将无符号整数类型分配给 boost::any
(或 std::any
,它做同样的事情,但语法略有不同)。
When I tried using
boost::any_cast<uint8_t>()
it did not print, but did not throw an error.
那不会“打印”一个\0
吗?特点?所以看起来好像什么都没打印。
Is it possible to get the value of a type like
uint8_t
using Boost? If so how?
正如您所期望的那样:
uint8_t u = 234;
boost::any ba = u;
std::cout << "u is " << (int) boost::any_cast<uint8_t>(ba) << '\n';
关于c++ - boost::any 结构和无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071956/