MSVC 中的复合文字

2023-03-09C/C++开发问题
2

本文介绍了MSVC 中的复合文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 GCC 中,我可以这样做:

In GCC, I'm able to do this:

(CachedPath){ino}
inode->data = (struct Data)DATA_INIT;

哪里:

struct CachedPath
{
    Ino ino;
};

typedef int8_t Depth;
struct Data
{
    Offset size;
    Blkno root;
    Depth depth;
};
#define DATA_INIT {0, -1, 0}

MSVC 为这些类型的转换提供以下错误:

MSVC gives the following error for these kind of casts:

error C2143: syntax error : missing ';' before '{'

如何在 MSVC 中执行此操作? 进一步注意,代码已从 C99 转换而来,我为此使用了指定的初始值设定项,然后进行了类似的转换.任何有关 C99 和 C++ 的 MSVC/GCC 实现之间的各种功能之间关系的清晰性表示赞赏.

How can I do this in MSVC? Further note that the code has been converted from C99, where I used designated initializers for this, and then cast it similarly. Any clarity on how these various features relate between C99, and MSVC/GCC implementations of C++ is appreciated.

推荐答案

构造 (Type){initialisers} 不是强制转换操作,而是复合的句法构造字面意思.这是一个 C99 构造,GCC 在其 C++ 编译器中也支持它作为扩展.据我所知,在 C 或 C++ 模式下,直到并包括 MSVC 2012 都不支持复合文字.对 C 模式的支持是后来在 MSVC 2013 中引入的.在 C++ 模式下仍然不支持,我认为不太可能会添加支持.

The construct (Type){initialisers} is not a cast operation, but it is the syntactic construct of a compound literal. This is a C99 construct, which GCC also supports in its C++ compiler as an extension. As far as I can determine, compound literals are not supported up to and including MSVC 2012, in either its C or C++ mode. The support in C mode was introduced later, in MSVC 2013. In C++ mode it is still not supported and I believe it is unlikely support will be added.

对于 MSVC 2012 及更早版本,此构造的替代方案是

For MSVC 2012 and older, the alternatives for this construct are

  • 显式声明和初始化所需结构类型的临时对象,并在赋值中使用它而不是复合字面量
  • 不要对复合文字进行单一赋值,而是为每个单独的成员使用单独的赋值.

这篇关于MSVC 中的复合文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6