克服 Visual Studio 2013 中的 decltype 问题

Posted

技术标签:

【中文标题】克服 Visual Studio 2013 中的 decltype 问题【英文标题】:Overcoming decltype Issues in Visual Studio 2013 【发布时间】:2016-08-03 20:53:05 【问题描述】:

我一直在使用@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() 的调用,因为有几个与该函数和 VS 2013 相关的 SO 问题以及几个不同的解决方法:

[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[][] 对象使其不是数组似乎没有帮助。

【问题讨论】:

目前升级不是一种选择。 -- 也许你正试图从石头中挤出血液。 VS 2013 编译器就是这样,不会升级/修复。 是的,这是一种明显的可能性,尽管我希望对编译器错误有更多了解的人可以指出我在一些链接问题中的解决方法。 作为解决方法,您可以在 FIELD 中添加额外的参数,对应于decltype(data) 【参考方案1】:

我想知道 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);

在http://ideone.com/yWnlJu查看结果

【讨论】:

以上是关于克服 Visual Studio 2013 中的 decltype 问题的主要内容,如果未能解决你的问题,请参考以下文章