c++ - boost::any 结构和无符号整数

标签 c++ c++11 boost unsigned-integer boost-any

我的问题有几个部分。我一直在研究如何/何时使用 boost::any .我想知道是否可以分配一个 structboost::any变量。

示例:

struct S {
   int x;
};

S s;
s.x = 5;

boost::any var = s;

在我看来这是可能的,但它引出了我的下一个问题。如果这是一个有效的分配,那么我将如何访问数据成员 xvar不是 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 type uint8_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';

does indeed work .

关于c++ - boost::any 结构和无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071956/

相关文章:

javascript - 无法从 QML/JavaScript 函数读取 QStringList

C++ - 开发自己的 std::count_if 版本

c++ - boost spirit 莱克斯和气。集成跳过解析器

c++ - boost program_options 多值问题

c++ - ublas 矩阵表达式教程/示例

c++ - 图形工具:在 Linux 中编译并连接到本地 CGAL 库? (没有须藤)

c++11 信号系统

c++ - 如何在 boost::multi_index::multi_index_container 中存储元素?

c++ - 在linux/mac中获取一个多字节字符的 "char"

C++11/14 和 return( ... ) 与 return