无法使用 sizeof(成员变量)初始化 Visual Studio 中的静态常量值

Cannot use sizeof(member variable) to initialize a static const value in Visual Studio

我一直在使用 g++ 5.3.1 在 Fedora 23 box 上开发一个库,并使用 mingw 在 Windows box 上成功构建它(如有必要,我可以在此处获取版本)。今天我把这段代码交给了一位有兴趣使用它的同事。他在 Visual Studio 2013 年尝试编译它(他的 IDE 选择),但它失败了。下面我创建了一个问题的 MCVE:

#include "stdafx.h"  // include this while in Visual Studio
#include <iostream>  // include when compiling with g++

class staticTest
{
public:
  staticTest() { };
  ~staticTest() { };

  unsigned myVal;

private:
  static const size_t staticLength = sizeof(myVal);  // errors in VS2013, compiles fine with g++ and mingw
  const size_t length_ = sizeof(myVal);  // compiles fine for all
};

此编译没有错误或警告 g++ -Wall -Wextra -std=c++11 -c staticTest.cpp。但是,在 Visual Studio 2013 年,我收到以下关于 staticLength 分配行的 3 个错误:

statictest.cpp(12): error C2327: 'staticTest::myVal' : is not a type name, static, or enumerator
statictest.cpp(12): error C2065: 'myVal' : undeclared identifier
statictest.cpp(12): error C2070: 'unknown-type': illegal sizeof operand

我知道错误基本上是在说什么,它在 static 上下文中看不到成员变量,因此无法对其应用 sizeof 运算符。通过咬紧牙关,我批准将所有此类实例更改为 static const size_t staticLength = sizeof(unsigned);,之后它构建良好。这个问题在另一个例子中更加复杂,我尝试在 static 函数中使用 sizeof(memberArray)sizeof(memberArray[0]).

做类似的事情

我假设这是符合标准的,因为 g++ 喜欢它,而且我之前听说 Microsoft 编译器不符合标准,接受一种 pseudo-c/c++ 语言。

  1. 这是糟糕的编码风格吗?我总是更喜欢使用 sizeof(myVariable),因为它更易于维护(如果 myVariable 的类型发生变化,则 sizeof 无需更改)。在我看来,编译器应该在编译时知道(就像 g++ 那样)myVal 的类型,而不关心它是否是 class 的成员。
  2. 是否有人知道 Visual Studio 2013 中的解决方法,或者此问题是否已在 Visual Studio 的更高版本中得到解决?对我来说真正的问题是 Windows mingw 编译得很好,但我的同事不会从 VS 中让步,所以我在这里修改我的代码,使其不易维护,只是为了符合一个奇怪的想法IDE/compiler。哦,他的最终可执行文件将在与我的同一个盒子上为 Linux 和 运行 构建,因此甚至不需要或不需要在 VS 中构建它... [angry/puking emoji ]

编辑 我也试过:

static const size_t staticLength = sizeof(this->myVal);

static const size_t staticLength = sizeof(staticTest::myVal);

都失败了。

这适用于我的 Visual Studio 编译器:

static const size_t staticLength = sizeof(decltype(myVal)); 

据我所知,这应该适应对 myVal 类型的任何更改。

如果您不必在 class 定义中初始化它,请不要在 class 中初始化并具有:

const size_t staticTest::staticLength = sizeof staticTest::myVal;

在 .cpp 文件中