我一直在使用@ddriver提供的优秀位处理示例:
#define GETMASK(index, size) (((1 << (size)) - 1) << (index))
#define READFROM(data, index, size) (((data) & GETMASK((index), (size))) >> (index))
#define WRITETO(data, index, size, value) ((data) = ((data) & (~GETMASK((index), (size)))) | ((value) << (index)))
#define FIELD(data, name, index, size) \
inline decltype(data) name() { return READFROM(data, index, size); } \
inline void set_##name(decltype(data) value) { WRITETO(data, index, size, value); }
取自:How to read/write arbitrary bits in C/C++,做一些惊人而美妙的事情。
我遇到的问题是我的大部分开发工作都是在VS 2015中完成的,上面的#defines工作得很好,但在VS 2013中没有,这是我的另一个开发环境,升级不是选项那一刻。
我很确定问题是对decltype()的调用,因为有几个与该函数有关的SO问题和VS 2013有几个不同的解决方法:
[Why is Visual Studio 2013 having trouble with this class member decltype?]
[C++ decltype fails to deduce type]
[Visual C++ - decltype as a return type of a class template's member function]
[VS2013 Intellisense doesn't understand decltype]
[How to use auto return and decltype when class members involved with c++11?]
很遗憾,我无法使用上述任何解决方案来解决我的问题,不涉及将环境升级到VS 2015.
任何帮助都将是非常感谢。
在编译类似于:
的内容时,会抛出我收到的错误FIELD(bytes[0][0].r, layer1a, 1, 8);
我收到以下错误:
error C2597: illegal reference to non-static member 'mBit::bP::bytes'
error C3867: 'mBit::bP::bytes': function call missing argument list; use '&mBit::bP::bytes' to create a pointer to member
error C2109: subscript requires array or pointer type
修改bytes [] []对象使其不是数组似乎没有帮助。
答案 0 :(得分:2)
我想知道decltype
对你做了什么,所以我试着稍微改写一下代码,这可能不是你想要的,因为类型总是uint64_t。
#include <stdint.h>
#include <stdio.h>
#define GETMASK(index, size) (((1ULL << (size)) - 1ULL) << (index))
#define READFROM(data, index, size) (((data) & GETMASK((index), (size))) >> (index))
#define WRITETO(data, index, size, value) ((data) = ((data) & (~GETMASK((index), (size)))) | ((value) << (index)))
#define FIELD(data, name, index, size) \
inline uint64_t name() { return READFROM(data, index, size); } \
inline void set_##name(uint64_t value) { WRITETO(data, index, size, value); }
struct A {
uint16_t bitData;
FIELD(bitData, one, 0, 1)
FIELD(bitData, two, 1, 2)
};
int main() {
struct A a;
a.bitData = 2;
uint16_t res = a.two();
a.set_two(3);
printf("res = %u\n", res);
printf("a = %u\n", a.bitData);
}
的结果